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(billing): warn when a downgrade shortens events retention (#125002)

Andy Zhao8927afefb912
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1395b549f282..2eaed96ff1c4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -16774,6 +16774,10 @@ snapshots:
hash: v1.k794b7964.eddb23813346927e8512cbed7ab76f72971736388fcffc35b3d81ea640805002.Yi1Rs7fyY7BomNzgzPgpSEpnoiPRLsCNuwvRfyaUPUw
scenes-other-billing--billing-unsubscribe-modal--light:
hash: v1.k794b7964.7cf10e46f5aa3302bc795dba3862dc39caa2d7cc2c3d92ce666a0468abafcc99.iK3nG33NnqwMkzWLZtgWxS8ulvgwfANb2xHhFJUQNSc
+ scenes-other-billing--billing-unsubscribe-modal-with-grandfathered-events-retention--dark:
+ hash: v1.k794b7964.6f7b0f25f8cefd29df3dd0afd77e5453dbc8b14710f7580716d5ce952614d044.Lp--KbPVE5v7D_imd_vxswvl_SPi3DYTh9SlSTcyTYE
+ scenes-other-billing--billing-unsubscribe-modal-with-grandfathered-events-retention--light:
+ hash: v1.k794b7964.979cb3b555fc84876881dcc2be3c88c7735263feb381647d75783ca920e0473d.HGrF-R6zk0loTpbU_KVBJ8xjHo02vjSGXg3jVVkt9f8
scenes-other-billing--billing-with-credit-cta--dark:
hash: v1.k794b7964.23945681b34a2f84c7162d639dc4abca8d0e08bd9284df41e17380a7a68cf863._aUuTLLQFXc6McIFJBmYHKv1ED-c24XE9NXnAL0VEAU
scenes-other-billing--billing-with-credit-cta--light:
diff --git a/frontend/src/lib/logic/billing/billingLogic.test.ts b/frontend/src/lib/logic/billing/billingLogic.test.ts
index a67b2d3b7a43..bd0c0cf73942 100644
--- a/frontend/src/lib/logic/billing/billingLogic.test.ts
+++ b/frontend/src/lib/logic/billing/billingLogic.test.ts
@@ -7,7 +7,11 @@ import posthog from 'posthog-js'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
-import { BillingAPIErrorCodes, billingLogic } from 'lib/logic/billing/billingLogic'
+import {
+ BillingAPIErrorCodes,
+ GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY,
+ billingLogic,
+} from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { organizationLogic } from 'scenes/organizationLogic'
@@ -881,4 +885,44 @@ describe('billingLogic', () => {
expect(billingLogic.values.unsubscribeError).toEqual({ detail: UNSUBSCRIBE_ERROR_DETAIL })
}
)
+
+ it.each([
+ {
+ name: 'another paid plan',
+ paidPlanKeys: ['paid-20240111'],
+ grandfathered: false,
+ planAfterPackageDowngrade: 'paid-20240111',
+ },
+ {
+ name: 'the 7-year plan while billing still offers it to new customers',
+ paidPlanKeys: [GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY],
+ grandfathered: false,
+ planAfterPackageDowngrade: GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY,
+ },
+ {
+ name: 'the 7-year plan once billing offers the 2-year plan',
+ paidPlanKeys: [GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY, 'paid-20261105'],
+ grandfathered: true,
+ planAfterPackageDowngrade: 'paid-20261105',
+ },
+ ])(
+ 'decides grandfathered events retention for $name',
+ async ({ paidPlanKeys, grandfathered, planAfterPackageDowngrade }) => {
+ const [freePlan, paidPlan] = billingJson.products[0].plans
+ const paidPlans = paidPlanKeys.map((plan_key, index) => ({
+ ...paidPlan,
+ plan_key,
+ current_plan: index === 0,
+ }))
+ billingState = billingWithProducts([productWithUsage(0.5, { plans: [freePlan, ...paidPlans] })])
+ billingLogic.mount()
+
+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()
+
+ expect(billingLogic.values.hasGrandfatheredEventsRetention).toBe(grandfathered)
+ expect(billingLogic.values.productAnalyticsPlanAfterPackageDowngrade?.plan_key).toBe(
+ planAfterPackageDowngrade
+ )
+ }
+ )
})
diff --git a/frontend/src/lib/logic/billing/billingLogic.tsx b/frontend/src/lib/logic/billing/billingLogic.tsx
index afcd45d1732c..509b40b2c930 100644
--- a/frontend/src/lib/logic/billing/billingLogic.tsx
+++ b/frontend/src/lib/logic/billing/billingLogic.tsx
@@ -47,6 +47,7 @@ import {
isMemberUsageSpendReadAccessEnabled,
} from './billingAccess'
import { isCompanionProduct } from './companionProducts'
+import { eventsRetentionMonths } from './eventsRetentionMonths'
import {
buildUsageLimitApproachingMessage,
buildUsageLimitReachedMessage,
@@ -56,6 +57,9 @@ import {
export const DEFAULT_ESTIMATED_MONTHLY_CREDIT_AMOUNT_USD = 500
+// in sync with GRANDFATHERED_EVENTS_RETENTION_PLAN in billing
+export const GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY = 'paid-20240404'
+
export const ALLOCATION_THRESHOLD_ALERT = 0.8 // Threshold to show warning of event usage near limit (aligned with the 80% billing warning email)
export const ALLOCATION_THRESHOLD_BLOCK = 1.2 // Threshold to block usage
@@ -286,9 +290,12 @@ export interface billingLogicValues {
status: string
}
creditOverviewLoading: boolean
+ currentEventsRetentionMonths: number | null
currentPlatformAddon: BillingProductV2AddonType | null
+ currentPlatformAddonPlan: BillingPlanType | null
effectiveBillingAlert: BillingAlertConfig | null
estimatedMonthlyCreditAmountUsd: number | null
+ hasGrandfatheredEventsRetention: boolean
hasSupportAddonPlan: boolean
isActivateLicenseSubmitting: boolean
isActivateLicenseValid: boolean
@@ -309,6 +316,10 @@ export interface billingLogicValues {
openInvoices: OpenInvoices | null
openInvoicesLoading: boolean
platformAddons: BillingProductV2AddonType[]
+ productAnalyticsFreePlan: BillingPlanType | null
+ productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null
+ productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
+ productAnalyticsPlans: BillingPlanType[]
productSpecificAlert: BillingAlertConfig | null
products: BillingProductV2Type[]
productsLoading: boolean
@@ -672,6 +683,20 @@ export interface billingLogicMeta {
hasSupportAddonPlan: (billing: BillingType | null) => boolean
platformAddons: (billing: BillingType | null) => BillingProductV2AddonType[]
currentPlatformAddon: (billing: BillingType | null) => BillingProductV2AddonType | null
+ currentPlatformAddonPlan: (currentPlatformAddon: BillingProductV2AddonType | null) => BillingPlanType | null
+ productAnalyticsPlans: (billing: BillingType | null) => BillingPlanType[]
+ productAnalyticsFreePlan: (productAnalyticsPlans: BillingPlanType[]) => BillingPlanType | null
+ productAnalyticsPlanReplacingGrandfathered: (productAnalyticsPlans: BillingPlanType[]) => BillingPlanType | null
+ hasGrandfatheredEventsRetention: (
+ productAnalyticsPlans: BillingPlanType[],
+ productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
+ ) => boolean
+ productAnalyticsPlanAfterPackageDowngrade: (
+ productAnalyticsPlans: BillingPlanType[],
+ hasGrandfatheredEventsRetention: boolean,
+ productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
+ ) => BillingPlanType | null
+ currentEventsRetentionMonths: (currentOrganization: OrganizationType | null) => number | null
unusedPlatformAddonAmount: (
currentPlatformAddon: BillingProductV2AddonType | null,
timeRemainingInSeconds: number,
@@ -1255,6 +1280,61 @@ export const billingLogic = kea<billingLogicType>([
return platformProduct?.addons?.find((addon: BillingProductV2AddonType) => !!addon.subscribed) || null
},
],
+ currentPlatformAddonPlan: [
+ (s) => [s.currentPlatformAddon],
+ (currentPlatformAddon: BillingProductV2AddonType | null): BillingPlanType | null =>
+ currentPlatformAddon?.plans?.find((plan) => plan.current_plan) ??
+ currentPlatformAddon?.plans?.[0] ??
+ null,
+ ],
+ productAnalyticsPlans: [
+ (s) => [s.billing],
+ (billing: BillingType | null): BillingPlanType[] =>
+ billing?.products?.find((product) => product.type === ProductKey.PRODUCT_ANALYTICS)?.plans ?? [],
+ ],
+ productAnalyticsFreePlan: [
+ (s) => [s.productAnalyticsPlans],
+ (productAnalyticsPlans: BillingPlanType[]): BillingPlanType | null =>
+ productAnalyticsPlans.find((plan) => !!plan.free_allocation && !plan.tiers) ?? null,
+ ],
+ productAnalyticsPlanReplacingGrandfathered: [
+ (s) => [s.productAnalyticsPlans],
+ (productAnalyticsPlans: BillingPlanType[]): BillingPlanType | null =>
+ productAnalyticsPlans.find(
+ (plan) => !!plan.tiers && plan.plan_key !== GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY
+ ) ?? null,
+ ],
+ hasGrandfatheredEventsRetention: [
+ (s) => [s.productAnalyticsPlans, s.productAnalyticsPlanReplacingGrandfathered],
+ (
+ productAnalyticsPlans: BillingPlanType[],
+ productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
+ ): boolean =>
+ !!productAnalyticsPlanReplacingGrandfathered &&
+ productAnalyticsPlans.some(
+ (plan) => !!plan.current_plan && plan.plan_key === GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY
+ ),
+ ],
+ productAnalyticsPlanAfterPackageDowngrade: [
+ (s) => [
+ s.productAnalyticsPlans,
+ s.hasGrandfatheredEventsRetention,
+ s.productAnalyticsPlanReplacingGrandfathered,
+ ],
+ (
+ productAnalyticsPlans: BillingPlanType[],
+ hasGrandfatheredEventsRetention: boolean,
+ productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
+ ): BillingPlanType | null =>
+ hasGrandfatheredEventsRetention
+ ? productAnalyticsPlanReplacingGrandfathered
+ : (productAnalyticsPlans.find((plan) => !!plan.current_plan) ?? null),
+ ],
+ currentEventsRetentionMonths: [
+ (s) => [s.currentOrganization],
+ (currentOrganization: OrganizationType | null): number | null =>
+ eventsRetentionMonths(currentOrganization?.available_product_features),
+ ],
unusedPlatformAddonAmount: [
(s) => [s.currentPlatformAddon, s.timeRemainingInSeconds, s.timeTotalInSeconds],
(
diff --git a/frontend/src/lib/logic/billing/eventsRetentionMonths.test.ts b/frontend/src/lib/logic/billing/eventsRetentionMonths.test.ts
new file mode 100644
index 000000000000..fd9de548d865
--- /dev/null
+++ b/frontend/src/lib/logic/billing/eventsRetentionMonths.test.ts
@@ -0,0 +1,19 @@
+import { AvailableFeature, BillingPlanType } from '~/types'
+
+import { longestEventsRetentionMonths } from './eventsRetentionMonths'
+
+const planKeeping = (limit: number, unit: string): BillingPlanType =>
+ ({
+ features: [{ key: AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION, name: 'Data retention', limit, unit }],
+ }) as BillingPlanType
+
+describe('longestEventsRetentionMonths', () => {
+ it.each([
+ ['a year in months', [planKeeping(1, 'year')], 12],
+ ['the longer of two plans', [planKeeping(3, 'months'), planKeeping(2, 'years')], 24],
+ ['no plans', [null, undefined], null],
+ ['a plan without events retention', [{ features: [] } as unknown as BillingPlanType], null],
+ ])('counts %s', (_, plans, months) => {
+ expect(longestEventsRetentionMonths(plans)).toBe(months)
+ })
+})
diff --git a/frontend/src/lib/logic/billing/eventsRetentionMonths.ts b/frontend/src/lib/logic/billing/eventsRetentionMonths.ts
new file mode 100644
index 000000000000..2a73bb04a77c
--- /dev/null
+++ b/frontend/src/lib/logic/billing/eventsRetentionMonths.ts
@@ -0,0 +1,16 @@
+import { AvailableFeature, BillingFeatureType, BillingPlanType } from '~/types'
+
+const MONTHS_PER_UNIT: Record<string, number> = { month: 1, months: 1, year: 12, years: 12 }
+
+export function eventsRetentionMonths(features: BillingFeatureType[] | null | undefined): number | null {
+ const feature = features?.find((feature) => feature.key === AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION)
+ const monthsPerUnit = feature?.unit ? MONTHS_PER_UNIT[feature.unit] : undefined
+ return feature?.limit && monthsPerUnit ? feature.limit * monthsPerUnit : null
+}
+
+export function longestEventsRetentionMonths(plans: (BillingPlanType | null | undefined)[]): number | null {
+ const months = plans
+ .map((plan) => eventsRetentionMonths(plan?.features))
+ .filter((value): value is number => value !== null)
+ return months.length ? Math.max(...months) : null
+}
diff --git a/frontend/src/scenes/billing/Billing.stories.tsx b/frontend/src/scenes/billing/Billing.stories.tsx
index d1ed26f6d11b..b09b44ab8798 100644
--- a/frontend/src/scenes/billing/Billing.stories.tsx
+++ b/frontend/src/scenes/billing/Billing.stories.tsx
@@ -1,6 +1,9 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import { Meta, StoryObj } from '@storybook/react'
import { dayjs } from 'lib/dayjs'
+import { GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY } from 'lib/logic/billing/billingLogic'
import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
import { billingJson } from '~/mocks/fixtures/_billing'
@@ -9,7 +12,7 @@ import billingJsonWith100PercentDiscount from '~/mocks/fixtures/_billing_with_10
import billingJsonWithCredits from '~/mocks/fixtures/_billing_with_credits.json'
import billingJsonWithDiscount from '~/mocks/fixtures/_billing_with_discount.json'
import preflightJson from '~/mocks/fixtures/_preflight.json'
-import { BillingProvider, BillingType, StartupProgramLabel } from '~/types'
+import { AvailableFeature, BillingProvider, BillingType, StartupProgramLabel } from '~/types'
import { Billing } from './Billing'
import { PurchaseCreditsModal } from './PurchaseCreditsModal'
@@ -26,6 +29,25 @@ const billingJsonWithoutIconKeys: BillingType = {
})),
}
+const billingJsonWithGrandfatheredEventsRetention: BillingType = {
+ ...billingJson,
+ products: billingJson.products.map((product) =>
+ product.type === 'product_analytics'
+ ? {
+ ...product,
+ plans: product.plans.flatMap((plan) =>
+ plan.current_plan
+ ? [
+ { ...plan, plan_key: GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY },
+ { ...plan, plan_key: 'paid-20261105', current_plan: false },
+ ]
+ : [plan]
+ ),
+ }
+ : product
+ ),
+}
+
const VERCEL_INVOICES_URL = 'https://vercel.com/example-team/~/integrations/posthog/icfg_example/invoices'
const meta: Meta = {
@@ -300,3 +322,49 @@ export const BillingUnsubscribeModal: Story = {
return <UnsubscribeSurveyModal product={billingJson.products[0]} />
},
}
+
+export const BillingUnsubscribeModalShorteningEventsRetention: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/organizations/@current/': {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: [
+ {
+ key: AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION,
+ name: 'Data retention',
+ limit: 7,
+ unit: 'years',
+ },
+ ],
+ },
+ '/api/organizations/:organization_id/events_retention_setting/downgrade_deletion_count/': {
+ retention_months: 12,
+ events_deleted: 1234567,
+ },
+ },
+ }),
+ ],
+ parameters: { testOptions: { snapshotBrowsers: [] } },
+ render: () => {
+ useStorybookMocks({ get: { '/api/billing/': billingJson } })
+
+ return <UnsubscribeSurveyModal product={billingJson.products[0]} />
+ },
+}
+
+export const BillingUnsubscribeModalWithGrandfatheredEventsRetention: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ '/api/billing/': billingJsonWithGrandfatheredEventsRetention,
+ '/api/organizations/:organization_id/events_retention_setting/downgrade_deletion_count/': {
+ retention_months: 12,
+ events_deleted: 1234567,
+ },
+ },
+ })
+
+ return <UnsubscribeSurveyModal product={billingJsonWithGrandfatheredEventsRetention.products[0]} />
+ },
+}
diff --git a/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx b/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx
index 5dc0585dc51d..73635e79699a 100644
--- a/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx
+++ b/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx
@@ -10,9 +10,16 @@ import { BillingInvoiceItemRow, BillingProductV2AddonType } from '~/types'
import { AddonFeatureLossNotice } from './AddonFeatureLossNotice'
import { billingProductLogic } from './billingProductLogic'
+import { EventsRetentionDowngradeNotice } from './EventsRetentionDowngradeNotice'
export function ConfirmDowngradeModal({ product }: { product: BillingProductV2AddonType }): JSX.Element | null {
- const { currentPlatformAddon, unusedPlatformAddonAmount, switchPlanLoading, billing } = useValues(billingLogic)
+ const {
+ currentPlatformAddon,
+ unusedPlatformAddonAmount,
+ switchPlanLoading,
+ billing,
+ productAnalyticsPlanAfterPackageDowngrade,
+ } = useValues(billingLogic)
const { currentAndUpgradePlans, confirmDowngradeModalOpen, proratedAmount } = useValues(
billingProductLogic({ product })
)
@@ -105,6 +112,10 @@ export function ConfirmDowngradeModal({ product }: { product: BillingProductV2Ad
</p>
<AddonFeatureLossNotice product={currentPlatformAddon} targetProduct={product} />
+ <EventsRetentionDowngradeNotice
+ plansAfterChange={[targetPlan, productAnalyticsPlanAfterPackageDowngrade]}
+ className="mt-2"
+ />
<LemonTable dataSource={rows} columns={columns} className="mt-4" uppercaseHeader={false} />
diff --git a/frontend/src/scenes/billing/EventsRetentionDowngradeNotice.tsx b/frontend/src/scenes/billing/EventsRetentionDowngradeNotice.tsx
new file mode 100644
index 000000000000..8e5947cf0b35
--- /dev/null
+++ b/frontend/src/scenes/billing/EventsRetentionDowngradeNotice.tsx
@@ -0,0 +1,43 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { billingLogic } from 'lib/logic/billing/billingLogic'
+import { longestEventsRetentionMonths } from 'lib/logic/billing/eventsRetentionMonths'
+
+import { BillingPlanType } from '~/types'
+
+import { EventsRetentionDowngradeDeletionCount } from 'products/product_analytics/frontend/settings/EventsRetentionDowngradeDeletionCount'
+import { retentionPeriodLabel } from 'products/product_analytics/frontend/settings/retentionPeriodLabel'
+
+export function EventsRetentionDowngradeNotice({
+ plansAfterChange,
+ className,
+}: {
+ plansAfterChange: (BillingPlanType | null | undefined)[]
+ className?: string
+}): JSX.Element | null {
+ const { hasGrandfatheredEventsRetention, currentEventsRetentionMonths } = useValues(billingLogic)
+ const newMonths = longestEventsRetentionMonths(plansAfterChange)
+
+ let message: string
+ if (hasGrandfatheredEventsRetention) {
+ message =
+ 'Your organization keeps 7 years of events data retention from an older plan. This change ends that permanently, and your events data retention follows your new plan.'
+ } else if (
+ newMonths !== null &&
+ currentEventsRetentionMonths !== null &&
+ newMonths < currentEventsRetentionMonths
+ ) {
+ message = `This change shortens your events data retention from ${retentionPeriodLabel(currentEventsRetentionMonths)} to ${retentionPeriodLabel(newMonths)}.`
+ } else {
+ return null
+ }
+
+ return (
+ <LemonBanner type="warning" className={className}>
+ <p className="mb-0">{message}</p>
+ {newMonths !== null && <EventsRetentionDowngradeDeletionCount months={newMonths} />}
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
index 09590e4c5855..27f83045fd36 100644
--- a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
+++ b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
@@ -34,6 +34,7 @@ import {
isPlatformAndSupportAddon,
randomizeReasons,
} from './billingProductLogic'
+import { EventsRetentionDowngradeNotice } from './EventsRetentionDowngradeNotice'
const HedgehogHeart = pngHoggie(heartPng)
@@ -44,9 +45,15 @@ export const UnsubscribeSurveyModal = ({
}): JSX.Element | null => {
const { trigger, HogfettiComponent } = useHogfetti()
- const { surveyID, surveyResponse, isAddonProduct, unsubscribeModalStep, unsubscribeReasonQuestions } = useValues(
- billingProductLogic({ product, hogfettiTrigger: trigger })
- )
+ const {
+ surveyID,
+ surveyResponse,
+ isAddonProduct,
+ unsubscribeModalStep,
+ unsubscribeReasonQuestions,
+ productsToDeactivate,
+ eventsRetentionPlansAfterUnsubscribe,
+ } = useValues(billingProductLogic({ product, hogfettiTrigger: trigger }))
const {
setSurveyResponse,
toggleSurveyReason,
@@ -81,7 +88,7 @@ export const UnsubscribeSurveyModal = ({
setUnsubscribeModalStep(2)
triggerMoreHedgehogs()
} else {
- deactivateProduct(billing?.subscription_level === 'paid' && !isAddonProduct ? 'all_products' : product.type)
+ deactivateProduct(productsToDeactivate)
}
}
@@ -106,9 +113,7 @@ export const UnsubscribeSurveyModal = ({
loading={billingLoading}
onClick={() => {
setHedgehogSatisfied(true)
- deactivateProduct(
- billing?.subscription_level === 'paid' && !isAddonProduct ? 'all_products' : product.type
- )
+ deactivateProduct(productsToDeactivate)
}}
>
Never enough, proceed with {action}
@@ -213,6 +218,9 @@ export const UnsubscribeSurveyModal = ({
)}
{isPlatformAndSupportAddon(product) && <AddonFeatureLossNotice product={product} />}
+ {eventsRetentionPlansAfterUnsubscribe && (
+ <EventsRetentionDowngradeNotice plansAfterChange={eventsRetentionPlansAfterUnsubscribe} />
+ )}
<LemonLabel>
{billing?.subscription_level === 'paid'
diff --git a/frontend/src/scenes/billing/billingProductLogic.test.ts b/frontend/src/scenes/billing/billingProductLogic.test.ts
index ef5a5a411433..4cb9bd35ebec 100644
--- a/frontend/src/scenes/billing/billingProductLogic.test.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.test.ts
@@ -271,6 +271,69 @@ describe('billingProductLogic', () => {
})
describe('unsubscribe survey state', () => {
+ it.each([
+ {
+ name: 'cancelling a paid plan',
+ subscriptionLevel: 'paid' as const,
+ productType: 'product_analytics',
+ expected: ['free-20230117'],
+ },
+ {
+ name: 'unsubscribing from product analytics alone',
+ subscriptionLevel: 'custom' as const,
+ productType: 'product_analytics',
+ expected: ['free-20230117', 'scale-addon-20250429'],
+ },
+ {
+ name: 'removing the platform package',
+ subscriptionLevel: 'paid' as const,
+ productType: BillingPlan.Scale,
+ expected: ['paid-20240111'],
+ },
+ {
+ name: 'unsubscribing from another product',
+ subscriptionLevel: 'custom' as const,
+ productType: 'session_replay',
+ expected: null,
+ },
+ ])(
+ 'compares events retention against the plans left after $name',
+ async ({ subscriptionLevel, productType, expected }) => {
+ const subscribedScale: BillingProductV2AddonType = {
+ ...scaleAddon,
+ subscribed: true,
+ plans: scaleAddon.plans.map((plan) => ({ ...plan, current_plan: true })),
+ }
+ useMocks({
+ get: {
+ '/api/billing': () => [
+ 200,
+ {
+ ...billingJson,
+ subscription_level: subscriptionLevel,
+ products: billingJson.products.map((product) =>
+ product.type === 'platform_and_support'
+ ? { ...product, addons: [subscribedScale] }
+ : product
+ ),
+ },
+ ],
+ },
+ })
+ billingLogic.mount()
+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()
+ const logic = billingProductLogic({
+ product: productType === BillingPlan.Scale ? subscribedScale : productByType(productType),
+ })
+ logic.mount()
+ mounted.push(logic)
+
+ expect(
+ logic.values.eventsRetentionPlansAfterUnsubscribe?.map((plan) => plan?.plan_key ?? null) ?? null
+ ).toEqual(expected)
+ }
+ )
+
it('keeps survey responses isolated per product type', async () => {
await seedBilling({})
const analytics = mountProduct('product_analytics')
diff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.ts
index d3b1394aadb9..1782b444a595 100644
--- a/frontend/src/scenes/billing/billingProductLogic.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.ts
@@ -25,7 +25,7 @@ import {
} from '~/types'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
-import type { ProductKey } from '../../queries/schema/schema-general'
+import { ProductKey } from '../../queries/schema/schema-general'
import {
calculateFreeTier,
canHaveBillingLimit,
@@ -100,8 +100,11 @@ export interface BillingProductLogicProps {
export interface billingProductLogicValues {
billing: BillingType | null // billingLogic
currentPlatformAddon: BillingProductV2AddonType | null // billingLogic
+ currentPlatformAddonPlan: BillingPlanType | null // billingLogic
isUnlicensedDebug: boolean // billingLogic
platformAddons: BillingProductV2AddonType[] // billingLogic
+ productAnalyticsFreePlan: BillingPlanType | null // billingLogic
+ productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null // billingLogic
scrollToProductKey: ProductKey | null // billingLogic
selfServeBillingNotice: string | null // billingLogic
timeRemainingInSeconds: number // billingLogic
@@ -146,6 +149,7 @@ export interface billingProductLogicValues {
upgradePlan: BillingPlanType
}
customLimitUsd: number | null
+ eventsRetentionPlansAfterUnsubscribe: (BillingPlanType | null)[] | null
freeTier: number
hasCustomLimitSet: boolean
hedgehogSatisfied: boolean
@@ -171,6 +175,7 @@ export interface billingProductLogicValues {
key: string
product: BillingProductV2AddonType | BillingProductV2Type
}> | null
+ productsToDeactivate: string
projectedAmountExcludingAddons: string
proratedAmount: number
removingBillingLimitNextPeriod: boolean
@@ -478,6 +483,18 @@ export interface billingProductLogicMeta {
billing: BillingType | null,
product: BillingProductV2AddonType | BillingProductV2Type
) => boolean
+ productsToDeactivate: (
+ billing: BillingType | null,
+ isAddonProduct: boolean,
+ product: BillingProductV2AddonType | BillingProductV2Type
+ ) => string
+ eventsRetentionPlansAfterUnsubscribe: (
+ product: BillingProductV2AddonType | BillingProductV2Type,
+ productsToDeactivate: string,
+ productAnalyticsFreePlan: BillingPlanType | null,
+ productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null,
+ currentPlatformAddonPlan: BillingPlanType | null
+ ) => (BillingPlanType | null)[] | null
unsubscribeReasonQuestions: (surveyResponse: {
$survey_response: string
$survey_response_2: string[]
@@ -590,6 +607,9 @@ export const billingProductLogic = kea<billingProductLogicType>([
'timeTotalInSeconds',
'unusedPlatformAddonAmount',
'selfServeBillingNotice',
+ 'productAnalyticsFreePlan',
+ 'productAnalyticsPlanAfterPackageDowngrade',
+ 'currentPlatformAddonPlan',
],
featureFlagLogic,
['featureFlags'],
@@ -1012,6 +1032,41 @@ export const billingProductLogic = kea<billingProductLogicType>([
(billing: BillingType | null, product: BillingProductV2AddonType | BillingProductV2Type): boolean =>
!!billing?.products?.some((p) => p.addons?.some((addon) => addon.type === product?.type)),
],
+ productsToDeactivate: [
+ (s, p) => [s.billing, s.isAddonProduct, p.product],
+ (
+ billing: BillingType | null,
+ isAddonProduct: boolean,
+ product: BillingProductV2AddonType | BillingProductV2Type
+ ): string => (billing?.subscription_level === 'paid' && !isAddonProduct ? 'all_products' : product.type),
+ ],
+ eventsRetentionPlansAfterUnsubscribe: [
+ (s, p) => [
+ p.product,
+ s.productsToDeactivate,
+ s.productAnalyticsFreePlan,
+ s.productAnalyticsPlanAfterPackageDowngrade,
+ s.currentPlatformAddonPlan,
+ ],
+ (
+ product: BillingProductV2AddonType | BillingProductV2Type,
+ productsToDeactivate: string,
+ productAnalyticsFreePlan: BillingPlanType | null,
+ productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null,
+ currentPlatformAddonPlan: BillingPlanType | null
+ ): (BillingPlanType | null)[] | null => {
+ if (isPlatformAndSupportAddon(product)) {
+ return [productAnalyticsPlanAfterPackageDowngrade]
+ }
+ if (productsToDeactivate === 'all_products') {
+ return [productAnalyticsFreePlan]
+ }
+ if (productsToDeactivate === ProductKey.PRODUCT_ANALYTICS) {
+ return [productAnalyticsFreePlan, currentPlatformAddonPlan]
+ }
+ return null
+ },
+ ],
unsubscribeReasonQuestions: [
(s) => [s.surveyResponse],
(surveyResponse: { $survey_response: string; $survey_response_2: string[] }): string => {
diff --git a/products/product_analytics/backend/events_retention.py b/products/product_analytics/backend/events_retention.py
index 323413cb9b10..3cd9a8af31a8 100644
--- a/products/product_analytics/backend/events_retention.py
+++ b/products/product_analytics/backend/events_retention.py
@@ -170,8 +170,8 @@ def project_events_retention(team: Team) -> ProjectEventsRetention:
)
-def _next_cleanup_cutoff(months: int) -> datetime:
- return whole_month_cutoff(datetime.combine(next_cleanup_on(), time()), months).replace(tzinfo=UTC)
+def _cutoff_on(deletes_on: date, months: int) -> datetime:
+ return whole_month_cutoff(datetime.combine(deletes_on, time()), months).replace(tzinfo=UTC)
def _events_before(team: Team, cutoff: datetime, seconds: int, concurrency_slots: ConcurrencySlots) -> int:
@@ -194,17 +194,36 @@ def _events_before(team: Team, cutoff: datetime, seconds: int, concurrency_slots
return count
+def _teams_events_before(teams: Iterable[Team], cutoff: datetime, concurrency_slots: ConcurrencySlots) -> int:
+ deadline = monotonic() + EVENTS_DELETED_QUERY_SECONDS
+ return sum(_events_before(team, cutoff, math.ceil(deadline - monotonic()), concurrency_slots) for team in teams)
+
+
def project_events_deleted(team: Team, months: int, *, concurrency_slots: ConcurrencySlots) -> int:
- return _events_before(team, _next_cleanup_cutoff(months), EVENTS_DELETED_QUERY_SECONDS, concurrency_slots)
+ return _events_before(team, _cutoff_on(next_cleanup_on(), months), EVENTS_DELETED_QUERY_SECONDS, concurrency_slots)
def organization_events_deleted(organization: Organization, months: int, *, concurrency_slots: ConcurrencySlots) -> int:
- cutoff = _next_cleanup_cutoff(months)
- deadline = monotonic() + EVENTS_DELETED_QUERY_SECONDS
teams = Team.objects.filter(organization_id=organization.id).exclude(
id__in=TeamEventsRetentionConfig.objects.filter(events_retention_months__isnull=False).values("team_id")
)
- return sum(_events_before(team, cutoff, math.ceil(deadline - monotonic()), concurrency_slots) for team in teams)
+ return _teams_events_before(teams, _cutoff_on(next_cleanup_on(), months), concurrency_slots)
+
+
+def organization_downgrade_events_deleted(
+ organization: Organization, months: int, *, concurrency_slots: ConcurrencySlots
+) -> int:
+ teams = list(Team.objects.filter(organization_id=organization.id))
+ kept = {
+ setting.team_id
+ for setting in effective_events_retention(team_ids=[team.id for team in teams])
+ if setting.months <= months
+ }
+ return _teams_events_before(
+ [team for team in teams if team.id not in kept],
+ _cutoff_on(next_pass_on(cleanup_date()), months),
+ concurrency_slots,
+ )
def _check_allowed(retention: OrganizationEventsRetention, months: int | None) -> None:
diff --git a/products/product_analytics/backend/facade/events_retention.py b/products/product_analytics/backend/facade/events_retention.py
index 8f5d0328c055..049513b35bd1 100644
--- a/products/product_analytics/backend/facade/events_retention.py
+++ b/products/product_analytics/backend/facade/events_retention.py
@@ -33,6 +33,14 @@ def organization_events_deleted(
return events_retention.organization_events_deleted(organization, months, concurrency_slots=concurrency_slots)
+def organization_downgrade_events_deleted(
+ organization: Organization, months: int, *, concurrency_slots: events_retention.ConcurrencySlots
+) -> int:
+ return events_retention.organization_downgrade_events_deleted(
+ organization, months, concurrency_slots=concurrency_slots
+ )
+
+
def set_organization_events_retention(
organization: Organization,
months: int | None,
diff --git a/products/product_analytics/backend/presentation/events_retention.py b/products/product_analytics/backend/presentation/events_retention.py
index 7f87313cc08b..01b317079171 100644
--- a/products/product_analytics/backend/presentation/events_retention.py
+++ b/products/product_analytics/backend/presentation/events_retention.py
@@ -18,6 +18,7 @@ from posthog.permissions import OrganizationAdminReadPermissions, OrganizationAd
from products.product_analytics.backend.facade.contracts import OrganizationEventsRetention
from products.product_analytics.backend.facade.events_retention import (
+ organization_downgrade_events_deleted,
organization_events_deleted,
organization_events_retention,
project_events_deleted,
@@ -151,8 +152,8 @@ class EventsDeletedSerializer(serializers.Serializer):
events_deleted = serializers.IntegerField(
read_only=True,
help_text=(
- "How many queryable events the next monthly cleanup deletes with this period. The count can be up to a "
- "day old."
+ "How many queryable events are older than the cutoff for this period. The endpoint says which "
+ "deletion sets the cutoff. The count can be up to a day old."
),
)
@@ -353,3 +354,32 @@ class OrganizationEventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSe
return _events_deleted_response(
months, organization_events_deleted(self.organization, months, concurrency_slots=query_concurrency_slots)
)
+
+ @validated_request(
+ query_serializer=EventsDeletedQuerySerializer,
+ operation_id="organization_events_retention_downgrade_deletion_count",
+ summary="Count the events a downgrade to a shorter period would delete",
+ description=(
+ "Counts the events that the deletion pass after a plan downgrade deletes if the organization's events "
+ "retention drops to retention_months, whether or not deletion is rolled out to the organization yet. Sums "
+ "the projects whose period is longer than retention_months. Organization admins only."
+ ),
+ responses={
+ 200: OpenApiResponse(response=EventsDeletedSerializer, description="The count."),
+ 403: OpenApiResponse(description="The user isn't an organization admin."),
+ 504: OpenApiResponse(description="The count took too long."),
+ },
+ )
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="downgrade_deletion_count",
+ required_scopes=["organization:read", "query:read"],
+ permission_classes=[OrganizationAdminReadPermissions],
+ )
+ def downgrade_deletion_count(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ months = request.validated_query_data["retention_months"]
+ return _events_deleted_response(
+ months,
+ organization_downgrade_events_deleted(self.organization, months, concurrency_slots=query_concurrency_slots),
+ )
diff --git a/products/product_analytics/backend/tests/api/test_events_retention.py b/products/product_analytics/backend/tests/api/test_events_retention.py
index 177bbd708c12..d1e9676caec5 100644
--- a/products/product_analytics/backend/tests/api/test_events_retention.py
+++ b/products/product_analytics/backend/tests/api/test_events_retention.py
@@ -319,19 +319,41 @@ class TestEventsRetentionAPI(APIBaseTest):
@parameterized.expand(
[
- ("project_admin", "project_admin", "project", 3, status.HTTP_403_FORBIDDEN),
- ("project_admin", "project_admin", "organization", 3, status.HTTP_403_FORBIDDEN),
- ("period_before_any_date", "organization_admin", "project", 100000, status.HTTP_400_BAD_REQUEST),
- ("period_before_any_date", "organization_admin", "organization", 100000, status.HTTP_400_BAD_REQUEST),
+ ("project_admin", "project_admin", "project", "deletion_count", 3, status.HTTP_403_FORBIDDEN),
+ ("project_admin", "project_admin", "organization", "deletion_count", 3, status.HTTP_403_FORBIDDEN),
+ (
+ "project_admin",
+ "project_admin",
+ "organization",
+ "downgrade_deletion_count",
+ 3,
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "period_before_any_date",
+ "organization_admin",
+ "project",
+ "deletion_count",
+ 100000,
+ status.HTTP_400_BAD_REQUEST,
+ ),
+ (
+ "period_before_any_date",
+ "organization_admin",
+ "organization",
+ "deletion_count",
+ 100000,
+ status.HTTP_400_BAD_REQUEST,
+ ),
]
)
def test_rejects_a_deletion_count(
- self, _name: str, level: str, scope: str, months: int, expected_status: int
+ self, _name: str, level: str, scope: str, count: str, months: int, expected_status: int
) -> None:
self._set_membership(level)
url = self.url() if scope == "project" else self.organization_url()
- response = self.client.get(f"{url}deletion_count/", {"retention_months": months})
+ response = self.client.get(f"{url}{count}/", {"retention_months": months})
assert response.status_code == expected_status
@@ -541,15 +563,43 @@ class TestEventsRetentionDeletionCountAPI(ClickhouseTestMixin, APIBaseTest):
assert project.json() == {"retention_months": 3, "events_deleted": 1}
assert organization.json() == {"retention_months": 3, "events_deleted": 3}
+ @time_machine.travel("2026-11-05T12:00:00Z", tick=False)
+ def test_counts_the_events_a_downgrade_deletes(self) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ shorter_period_team = Team.objects.create(organization=self.organization, name="Shorter period")
+ TeamEventsRetentionConfig.objects.create(team=shorter_period_team, events_retention_months=12)
+ longer_period_team = Team.objects.create(organization=self.organization, name="Longer period")
+ TeamEventsRetentionConfig.objects.create(team=longer_period_team, events_retention_months=24)
+ for team, timestamp in [
+ (self.team, "2026-02-28T23:59:59Z"),
+ (self.team, "2026-03-01T00:00:00Z"),
+ (shorter_period_team, "2026-01-01T00:00:00Z"),
+ (longer_period_team, "2026-01-01T00:00:00Z"),
+ ]:
+ _create_event(team=team, event="$pageview", distinct_id="user", timestamp=timestamp)
+
+ with override_settings(EVENTS_DATA_RETENTION_ENFORCED=False):
+ response = self.client.get(
+ f"/api/organizations/{self.organization.id}/events_retention_setting/downgrade_deletion_count/",
+ {"retention_months": 12},
+ )
+
+ assert response.json() == {"retention_months": 12, "events_deleted": 2}
+
@parameterized.expand(
[
- ("project", ["project:read"], status.HTTP_403_FORBIDDEN),
- ("project", ["project:read", "query:read"], status.HTTP_200_OK),
- ("organization", ["organization:read"], status.HTTP_403_FORBIDDEN),
- ("organization", ["organization:read", "query:read"], status.HTTP_200_OK),
+ ("project", "deletion_count", ["project:read"], status.HTTP_403_FORBIDDEN),
+ ("project", "deletion_count", ["project:read", "query:read"], status.HTTP_200_OK),
+ ("organization", "deletion_count", ["organization:read"], status.HTTP_403_FORBIDDEN),
+ ("organization", "deletion_count", ["organization:read", "query:read"], status.HTTP_200_OK),
+ ("organization", "downgrade_deletion_count", ["organization:read"], status.HTTP_403_FORBIDDEN),
+ ("organization", "downgrade_deletion_count", ["organization:read", "query:read"], status.HTTP_200_OK),
]
)
- def test_tokens_need_query_access_to_count(self, scope: str, scopes: list[str], expected_status: int) -> None:
+ def test_tokens_need_query_access_to_count(
+ self, scope: str, count: str, scopes: list[str], expected_status: int
+ ) -> None:
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
self.client.logout()
@@ -560,6 +610,6 @@ class TestEventsRetentionDeletionCountAPI(ClickhouseTestMixin, APIBaseTest):
else f"/api/organizations/{self.organization.id}/events_retention_setting/"
)
- response = self.client.get(f"{url}deletion_count/", {"retention_months": 3})
+ response = self.client.get(f"{url}{count}/", {"retention_months": 3})
assert response.status_code == expected_status
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index e98f4eede05f..2dea1faeb9c2 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -41,7 +41,7 @@ export interface EventsRetentionUpdateApi {
export interface EventsDeletedApi {
/** The period in months that was counted for. */
readonly retention_months: number
- /** How many queryable events the next monthly cleanup deletes with this period. The count can be up to a day old. */
+ /** How many queryable events are older than the cutoff for this period. The endpoint says which deletion sets the cutoff. The count can be up to a day old. */
readonly events_deleted: number
}
@@ -10138,6 +10138,15 @@ export type OrganizationEventsRetentionDeletionCountParams = {
retention_months: number
}
+export type OrganizationEventsRetentionDowngradeDeletionCountParams = {
+ /**
+ * The period in months to count for, at most 1200. Only events older than this period are counted.
+ * @minimum 1
+ * @maximum 1200
+ */
+ retention_months: number
+}
+
export type ColumnConfigurationsListParams = {
/**
* Return saved views for this context only.
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index b37a74c5bb0d..51ae68146147 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -56,6 +56,7 @@ import type {
InsightsViewedCreateParams,
OrganizationEventsRetentionApi,
OrganizationEventsRetentionDeletionCountParams,
+ OrganizationEventsRetentionDowngradeDeletionCountParams,
PaginatedColumnConfigurationListApi,
PaginatedElementListApi,
PaginatedInsightListApi,
@@ -157,6 +158,43 @@ export const organizationEventsRetentionDeletionCount = async (
})
}
+export const getOrganizationEventsRetentionDowngradeDeletionCountUrl = (
+ organizationId: string,
+ params: OrganizationEventsRetentionDowngradeDeletionCountParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/organizations/${organizationId}/events_retention_setting/downgrade_deletion_count/?${stringifiedParams}`
+ : `/api/organizations/${organizationId}/events_retention_setting/downgrade_deletion_count/`
+}
+
+/**
+ * Counts the events that the deletion pass after a plan downgrade deletes if the organization's events retention drops to retention_months, whether or not deletion is rolled out to the organization yet. Sums the projects whose period is longer than retention_months. Organization admins only.
+ * @summary Count the events a downgrade to a shorter period would delete
+ */
+export const organizationEventsRetentionDowngradeDeletionCount = async (
+ organizationId: string,
+ params: OrganizationEventsRetentionDowngradeDeletionCountParams,
+ options?: RequestInit
+): Promise<EventsDeletedApi> => {
+ return apiMutator<EventsDeletedApi>(
+ getOrganizationEventsRetentionDowngradeDeletionCountUrl(organizationId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getColumnConfigurationsListUrl = (projectId: string, params?: ColumnConfigurationsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsx b/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsx
index ebd4a0a2eb2f..fd9fb6b024a3 100644
--- a/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsx
+++ b/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsx
@@ -33,7 +33,7 @@ export function EventsRetentionChangeNote({
return (
<div className="flex flex-col gap-2">
<p className="mb-0">{`${scope} that are older than ${period} will be deleted, and deleted events can't be restored.`}</p>
- {deletion.monthly && <EventsRetentionDeletionCount level={level} months={months} />}
+ {deletion.monthly && <EventsRetentionDeletionCount count={level} months={months} />}
<p className="mb-0">{deletionTiming(period, deletion)}</p>
</div>
)
diff --git a/products/product_analytics/frontend/settings/EventsRetentionDeletionCount.tsx b/products/product_analytics/frontend/settings/EventsRetentionDeletionCount.tsx
index ffd6e2af8ac5..ed0cec5d42ef 100644
--- a/products/product_analytics/frontend/settings/EventsRetentionDeletionCount.tsx
+++ b/products/product_analytics/frontend/settings/EventsRetentionDeletionCount.tsx
@@ -1,8 +1,8 @@
import { useValues } from 'kea'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+import { eventsDeletedSentence } from './eventsDeletedSentence'
import {
EventsRetentionDeletionCountLogicProps,
eventsRetentionDeletionCountLogic,
@@ -26,9 +26,5 @@ export function EventsRetentionDeletionCount(props: EventsRetentionDeletionCount
if (eventsDeleted === 0) {
return <p className="mb-0">{`No events are older than ${retentionPeriodLabel(props.months)} yet.`}</p>
}
- return (
- <p className="mb-0 font-semibold">
- {`This would delete about ${humanFriendlyLargeNumber(eventsDeleted)} ${eventsDeleted === 1 ? 'event' : 'events'}.`}
- </p>
- )
+ return <p className="mb-0 font-semibold">{eventsDeletedSentence(eventsDeleted)}</p>
}
diff --git a/products/product_analytics/frontend/settings/EventsRetentionDowngradeDeletionCount.tsx b/products/product_analytics/frontend/settings/EventsRetentionDowngradeDeletionCount.tsx
new file mode 100644
index 000000000000..db808e406a44
--- /dev/null
+++ b/products/product_analytics/frontend/settings/EventsRetentionDowngradeDeletionCount.tsx
@@ -0,0 +1,13 @@
+import { useValues } from 'kea'
+
+import { eventsDeletedSentence } from './eventsDeletedSentence'
+import { eventsRetentionDeletionCountLogic } from './eventsRetentionDeletionCountLogic'
+
+export function EventsRetentionDowngradeDeletionCount({ months }: { months: number }): JSX.Element | null {
+ const { eventsDeleted } = useValues(eventsRetentionDeletionCountLogic({ count: 'downgrade', months }))
+
+ if (!eventsDeleted) {
+ return null
+ }
+ return <p className="mb-0 mt-2 font-semibold">{eventsDeletedSentence(eventsDeleted)}</p>
+}
diff --git a/products/product_analytics/frontend/settings/eventsDeletedSentence.ts b/products/product_analytics/frontend/settings/eventsDeletedSentence.ts
new file mode 100644
index 000000000000..ef50e26ffbb3
--- /dev/null
+++ b/products/product_analytics/frontend/settings/eventsDeletedSentence.ts
@@ -0,0 +1,5 @@
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+export function eventsDeletedSentence(eventsDeleted: number): string {
+ return `This would delete about ${humanFriendlyLargeNumber(eventsDeleted)} ${eventsDeleted === 1 ? 'event' : 'events'}.`
+}
diff --git a/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.test.ts b/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.test.ts
index 1f649eda68c4..77e063516bc7 100644
--- a/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.test.ts
+++ b/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.test.ts
@@ -3,7 +3,10 @@ import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { EventsRetentionLevel, eventsRetentionDeletionCountLogic } from './eventsRetentionDeletionCountLogic'
+import {
+ EventsRetentionDeletionCountKind,
+ eventsRetentionDeletionCountLogic,
+} from './eventsRetentionDeletionCountLogic'
const TIMED_OUT_MONTHS = 1
@@ -22,6 +25,7 @@ describe('eventsRetentionDeletionCountLogic', () => {
get: {
'/api/projects/:team_id/events_retention/deletion_count/': count(100),
'/api/organizations/:organization_id/events_retention_setting/deletion_count/': count(1000),
+ '/api/organizations/:organization_id/events_retention_setting/downgrade_deletion_count/': count(10),
},
})
initKeaTests()
@@ -30,12 +34,13 @@ describe('eventsRetentionDeletionCountLogic', () => {
it.each([
['project', 12, 1200],
['organization', 12, 12000],
+ ['downgrade', 12, 120],
['project', TIMED_OUT_MONTHS, null],
['organization', TIMED_OUT_MONTHS, null],
- ] as [EventsRetentionLevel, number, number | null][])(
+ ] as [EventsRetentionDeletionCountKind, number, number | null][])(
'counts the %s events %i months deletes',
- async (level, months, eventsDeleted) => {
- const logic = eventsRetentionDeletionCountLogic({ level, months })
+ async (count, months, eventsDeleted) => {
+ const logic = eventsRetentionDeletionCountLogic({ count, months })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
diff --git a/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.ts b/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.ts
index 5496bcf08885..98eb6543cd37 100644
--- a/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.ts
+++ b/products/product_analytics/frontend/settings/eventsRetentionDeletionCountLogic.ts
@@ -8,8 +8,10 @@ import * as api from 'products/product_analytics/frontend/generated/api'
export type EventsRetentionLevel = 'project' | 'organization'
+export type EventsRetentionDeletionCountKind = EventsRetentionLevel | 'downgrade'
+
export interface EventsRetentionDeletionCountLogicProps {
- level: EventsRetentionLevel
+ count: EventsRetentionDeletionCountKind
months: number
}
@@ -55,7 +57,7 @@ export type eventsRetentionDeletionCountLogicType = MakeLogicType<
export const eventsRetentionDeletionCountLogic: LogicWrapper<eventsRetentionDeletionCountLogicType> =
kea<eventsRetentionDeletionCountLogicType>([
props({} as EventsRetentionDeletionCountLogicProps),
- key(({ level, months }) => `${level}-${months}`),
+ key(({ count, months }) => `${count}-${months}`),
path((key) => [
'products',
'product_analytics',
@@ -73,14 +75,18 @@ export const eventsRetentionDeletionCountLogic: LogicWrapper<eventsRetentionDele
{
loadEventsDeleted: async () => {
const params = { retention_months: props.months }
+ const countEventsDeleted = {
+ project: () => api.eventsRetentionDeletionCount(String(values.currentTeamId), params),
+ organization: () =>
+ api.organizationEventsRetentionDeletionCount(values.currentOrganizationId, params),
+ downgrade: () =>
+ api.organizationEventsRetentionDowngradeDeletionCount(
+ values.currentOrganizationId,
+ params
+ ),
+ }[props.count]
try {
- const response =
- props.level === 'project'
- ? await api.eventsRetentionDeletionCount(String(values.currentTeamId), params)
- : await api.organizationEventsRetentionDeletionCount(
- values.currentOrganizationId,
- params
- )
+ const response = await countEventsDeleted()
return response.events_deleted
} catch {
return null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 09c7db6a5bc0..6587a41673ce 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42466,7 +42466,7 @@ export namespace Schemas {
export interface EventsDeleted {
/** The period in months that was counted for. */
readonly retention_months: number;
- /** How many queryable events the next monthly cleanup deletes with this period. The count can be up to a day old. */
+ /** How many queryable events are older than the cutoff for this period. The endpoint says which deletion sets the cutoff. The count can be up to a day old. */
readonly events_deleted: number;
}
@@ -121240,6 +121240,15 @@ export namespace Schemas {
retention_months: number;
};
+ export type OrganizationEventsRetentionDowngradeDeletionCountParams = {
+ /**
+ * The period in months to count for, at most 1200. Only events older than this period are counted.
+ * @minimum 1
+ * @maximum 1200
+ */
+ retention_months: number;
+ };
+
export type OrgFeatureFlagsKeysParams = {
/**
* Page size (max 100)