: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(retention): pick the events retention period in settings (#128748)
Andy Zhaob3ddc61b37fe
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d53234ac632c..867cbf742547 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14583,9 +14583,9 @@ snapshots:scenes-app-notebooks-run-all-banner--starting--light:hash: v1.k794b7964.6c7bd37efe1d58d68070782d7d1d0ce20be5abfebe1f829feb0376b584ad1158.CVBhfDqMZqLLuxmDgkiTAS9Vn2SANiX9cOWDF1Ui8hkscenes-app-notebooks-sql-cell-chart--bar-chart--dark:- hash: v1.k794b7964.640c7f77576390755335ffcb5a4758ae8c40e45e552cc582b83df90703ca3ce6.Z0us6XyXMiI63VquF3aewikkU6DlXcpQaTTDOJeE3CQ+ hash: v1.k794b7964.a5ae5623770373aa1dca622714757deb826025f36af8bddd3aaefe2c6a36ea8d.2CfBAx0IidNHW1GnSrF5UKPW0plPBq2BhKiO2VLnbiwscenes-app-notebooks-sql-cell-chart--bar-chart--light:- hash: v1.k794b7964.86951626f47e403f310125c96e5350afda1e0c0530378bd424507080e53bb050.hro623qzB_dGhkC3oRrWNGSdJTZzVdPRQvItVmGvfFI+ hash: v1.k794b7964.5d8e2302f99a364ebd159a1d78073c0f5502fbce0f4cffbf65c4b7c20bae625f.MOc106shcCf8x69XjTRORO540z084RtPmXMLZq8x9Coscenes-app-notebooks-sql-cell-chart--line-chart--dark:hash: v1.k794b7964.d0680bc106516aaf11e4f59df950c72ff97db4a45b842289c38e99982f5270e8.ZCfy8qhd-5cuv7pFdcsLTt9eMSzxmRTeOyX7HlVlhLIscenes-app-notebooks-sql-cell-chart--line-chart--light:@@ -15695,9 +15695,9 @@ snapshots:scenes-app-settings-environment--settings-environment-privacy--light:hash: v1.k794b7964.52575183df15ee111029b50d9a5699323a24f452953e188baf983fcec1128e1e._Xh6Gb8q1UZCF5MonVhd2fNxpHC8-_iep72Rt55Ep1Uscenes-app-settings-environment--settings-environment-product-analytics--dark:- hash: v1.k794b7964.df0493799d59c41f5cb90ed875263c900620f116ae8accdc706e8822ed09d623.kYP8xLaBlp7uXg048-qdFqCntE7dj4WvHUpeKz5Sol8+ hash: v1.k794b7964.c11e59ce895979abaf19782b6f124de1f2ce423d7bad8fa5dd1aaf97da8ff6a3.assJuIM4Wuv3nlrzqY9gEwAcZohCVDgSVPzUS4ph3G0scenes-app-settings-environment--settings-environment-product-analytics--light:- hash: v1.k794b7964.bc8bd49c7332cecdac4b27754e9d56612d75c80dfe68451587a345a3a5edac1e.pDIGPnwmF_rWUEAGuf4n_CdiNG5kX_tzcbMwkR_qKnM+ hash: v1.k794b7964.d366e07baf77aefdb0d2ff313fd1c21ad318c9fd1e640e1fcef6994d92935067.1XXoPVysbEl2s8nUCvwOWw3RtAgkrv8XG1dJgOG9FGwscenes-app-settings-environment--settings-environment-replay--dark:hash: v1.k794b7964.81aeaa4ffb47e8347ceccd2aecf68c51f1fbe9796fcd7fb75121dbe41e710ad2.kcBO_KCrWUs5KJM-V9drAfD9azOX95r-Nt2LN7VCuaMscenes-app-settings-environment--settings-environment-replay--light:@@ -15713,23 +15713,31 @@ snapshots:scenes-app-settings-environment--settings-environment-web-analytics--dark:hash: v1.k794b7964.9d6e5a0e4df6abe463f890e8d1512cb88362799c647b049c33c71ef9287872df.xVLOD_xlKjbFfq-_S4scEZySJiXJWq2Bi4f-wShS03Ascenes-app-settings-environment--settings-environment-web-analytics--light:- hash: v1.k794b7964.cb735c353087a7a5487e9f8b5a68b82ce19fafe4668b4a55211397868177d4a9.I_3_spCtwt30AjWW4NkUY4hfuqLWYv4v7iBspWjVh8M- scenes-app-settings-events-retention--organization-with-window--dark:- hash: v1.k794b7964.590456a7c33a470ea9ff4c24e944cb4788db20bda989ee4d9ba4f4de493f455a.Jisn6ZhWvAbOuITAEJArRXz7VITk6SqMlCaVaDTzd9A- scenes-app-settings-events-retention--organization-with-window--light:- hash: v1.k794b7964.6ceab57d3c2b5cfc45926bb347da12aff69189df7b61ffa59be5ff7943864e44.VUEXVuvYsL-uwVqw92v_2UMfvU2NOscdQ6h600_Xqn8- scenes-app-settings-events-retention--organization-without-window--dark:- hash: v1.k794b7964.b9ab252b1de3932da24dbbca690ef96ff87afdff992e737200eb530461ac2842.kSWJZkouRaHtSv-P3WvoWXM0MIdi1-gjjbWDnsTkoNw- scenes-app-settings-events-retention--organization-without-window--light:- hash: v1.k794b7964.aa70a345eee42b7d86118921393e0437f1ac8e8490087e8f28014ed717ce74a0.EstIEwAYjRB1vKjSziH_JX830M2lOjNe6M62_tF36fg- scenes-app-settings-events-retention--project-using-organization-window--dark:- hash: v1.k794b7964.bf5587730c42a2b73855238ee40f498994e4e876ec7cb983b175cf23dc02cd62.JksxVy9-zRdEYYPR7TcDlymGaeufm3ERJC5zOgVmIDQ- scenes-app-settings-events-retention--project-using-organization-window--light:- hash: v1.k794b7964.b634a9c5a3f9da024b8b2ac4a43e75d190206bdbad6cedf2945c6651f4e63459.hcAr1WGa3hs6SGZzlsm2LgiAmSaMMSbBZMNDeIPiWhE- scenes-app-settings-events-retention--project-with-own-window--dark:- hash: v1.k794b7964.75be029e0fec0ce60a40ba3ce392ecb8f1229caa2b36de18c0988f5972358224.7AKIj8bBPZ4GxGxkSz4OFkL2ecqRb2pQAtQDPuz9mKI- scenes-app-settings-events-retention--project-with-own-window--light:- hash: v1.k794b7964.d592697a1ed9083c5d81f6edb5c37cd27cb11788f924afe89da8cba612721cdc.oRuG2Nik5jxq_FHrFkpHdj4Zp7eQsViF169yTMkBJpA+ hash: v1.k794b7964.f943bb7f220b5641566bb172034d802c60a60e3170488aaf9be160be13460e80.qCNtLV2-xD30jkMOsMpr3TG43MtaRmOACCSUzeB8-iE+ scenes-app-settings-events-retention--organization-on-free-plan--dark:+ hash: v1.k794b7964.b075e1de23700cf59e5e17cc0dbe15496d9e7ee89677ca11110b5507b17da120.ud-PQDmvtjOEehGDRhgCKwok3Fivo8yrPTs1kHt81bU+ scenes-app-settings-events-retention--organization-on-free-plan--light:+ hash: v1.k794b7964.1538a5b5023d81082c4a245a5498a0f70a44a2e3fe04448ab155fe3574b6baac.RWmMKDsUvlOqlEN28fo1km3fP80fNYbq7XIVzTQdsb8+ scenes-app-settings-events-retention--organization-on-grandfathered-plan--dark:+ hash: v1.k794b7964.5311139faef8cf37fad26eeba16adb9a88c5ae1e46c49f3c7473a0e5f9686523.e97y8wSJ3pXxWtRy93YDkFPgK407gmXdqZKc66yveaw+ scenes-app-settings-events-retention--organization-on-grandfathered-plan--light:+ hash: v1.k794b7964.b6f168f7046609d662f9023a27c8d28921b7e1f3ba6f768d31dcd28862785747.fbQQL7TqYoGBOH4kp5lJNZUe5kKL0SNy8NerIPnGAow+ scenes-app-settings-events-retention--organization-with-period--dark:+ hash: v1.k794b7964.165e9b03a293c5ee6249f998ed36a2cfabf80ff67c1ea00471093085498d2315.kdBEWYevBrv63tAhIOQQ9h4u-BI1WLbpKsEcMFKctCw+ scenes-app-settings-events-retention--organization-with-period--light:+ hash: v1.k794b7964.f9f44cdd37ef8531e33a8e74cf6ee344a8bcd4ba797d7f5f5d426f1c41b915b0.FKSyT1L3_hDodtppsaX1lkLrx81qfS-tjjdtSX7UNwY+ scenes-app-settings-events-retention--organization-without-period--dark:+ hash: v1.k794b7964.c1f65c05625107a8ed095d01d89fdc6921de2701ea92e9879d40d8ebe63bd8ad.cfjZwS9viICOHj7ddHDZUmHp8VVnE-t1iELfoY1_62c+ scenes-app-settings-events-retention--organization-without-period--light:+ hash: v1.k794b7964.70b84417da61be49f74a1321cde10be43dd0838d2f1273b43cdef0c83d30c26e.knpupxV5SmTtLFZId8MYyZWJpm_AEryMMAT2kBP1u7Q+ scenes-app-settings-events-retention--project-using-organization-period--dark:+ hash: v1.k794b7964.229349004ef5468c3def133e850f08c7a28a57ef49663fe344f8c22d84048716.YwtOJlYaxCduvmLEriS0jyN1GDc6fT3gISX8gt_kF0g+ scenes-app-settings-events-retention--project-using-organization-period--light:+ hash: v1.k794b7964.b50e196abb2e7785a5d7c4c88c49583bbc3c848da114ea28be4fcd0a91eae30c.6lPa6cQKDSSVBSIASTBRa4qhBT6udZdSsa2rvduEXTY+ scenes-app-settings-events-retention--project-with-own-period--dark:+ hash: v1.k794b7964.568009db37ab7f7df4de9ba8543e040e1bf5cfc6d0aeed2d6342b1be41048d63.75oc5HCFJm4kFC5ZB28Bcpjn_7Tojly4nO8rRKNN6K4+ scenes-app-settings-events-retention--project-with-own-period--light:+ hash: v1.k794b7964.3c957dc5d92dff3513425f466865fd176cbcbfee6b09e7c060a84c549405acbc.ZCzmrgeTdAdr44h1YPLtCDtFiy0DmNaWdYg90VB-Gb8scenes-app-settings-identity-provider-configuration--oidc--dark:hash: v1.k794b7964.1177527533a6ec000b396e1ee39627722226aed5cbab11759198dbbc2d72dcb3.NqKVUNSdSz-yE-r1M5EiEIaPRbQwBbyjCAf7rSSi9Doscenes-app-settings-identity-provider-configuration--oidc--light:@@ -15775,13 +15783,13 @@ snapshots:scenes-app-settings-organization--settings-organization-danger-zone--light:hash: v1.k794b7964.47049e159f958a0d42bf69400030b50e718c5da6890e9467a328c3ed6e3e37bc.gSKYIxiKiBZBrNFbFPjqppAmyocGM5c4Iur9ADLtViYscenes-app-settings-organization--settings-organization-details--dark:- hash: v1.k794b7964.5ee9d366f67cdb58e27cfc9e89fdf60789c3b5f6a42dff761cb90c4a284c7b35.pQLwU4Lw3eCsLr4dtSAbN1JONBkIChleknyQX7SYp_k+ hash: v1.k794b7964.604706e6899037c43e49e829294361667dd05f505c3fefbdda1458eebc8b169b.OFOmgQC9lWgzXH1ICvzyyY5nSAWst6O7OyIIOqJLVxQscenes-app-settings-organization--settings-organization-details--light:- hash: v1.k794b7964.dc6dc3765b2abfdeb8032fe29b79f954de2a4afe844443f0a46ba7744ff1c1e6.CSMU-cdBqbbuCo82v1U98z9FvfvpY2kfAmtv7BxziW4+ hash: v1.k794b7964.6b710a60920169c832e3873e5d222f778ca2a104065d80d79f54175f87e7480f.bmg12j2uhYgaTf-tk29enBlIhLfcnjdoVRQ0JpIpW-oscenes-app-settings-organization--settings-organization-details-with-member-notice--dark:- hash: v1.k794b7964.b1f395bbf15d48c61333ab5a647b712ba01401e755bf9fb81f0ab4bba46f5680.tECjRtlQZ-uN1UZm-J-UYxEWGtQsSPx7eEGE0sz0oLw+ hash: v1.k794b7964.698db5d6e3188331db8be91a9dd79414d3d9d28213caa1396b9cec786d3da668.YEAET5iOokPh8WVJ9ml3TSlss3NwL7k9zet1Thc7SkMscenes-app-settings-organization--settings-organization-details-with-member-notice--light:- hash: v1.k794b7964.7cea108562b540ca7459ac39270ea56d782095f5c12898ff4dbd4929cef08648.rvSt7JTO7_ZqaXF0SXs7bX80S-oMkwaH8ZGXCCzdr0k+ hash: v1.k794b7964.a17ee63eecffc0e49d231380d3d8ec73abc8c107343f4b7dba2621b6dff122e2.GF8ElMwuoQ-2DqZxewyxLGz0m1WTMRHwnx5-mXAtTQ8scenes-app-settings-organization--settings-organization-members--dark:hash: v1.k794b7964.e750e1f4c754266afa20e4c43138ecf961d5a57d50b0ec8081c17339ca773e52.MpA-4kw4SUGZP6CXeibLZVAB447iJGmz5tdUixiYNjsscenes-app-settings-organization--settings-organization-members--light:@@ -15851,9 +15859,9 @@ snapshots:scenes-app-settings-project--settings-project-logs-read-only--light:hash: v1.k794b7964.e234f3e555bcb083ca96f00005f91ccccf94941d371c71497162169077ec1022.jNkdKOK2KaEq2T2jksEoVtN5Nupa3FuJLTe-npm0RIMscenes-app-settings-project--settings-project-product-analytics--dark:- hash: v1.k794b7964.2707b4b2aab6c4836114708669a0a517c4852690ac55341b9f32099debe27ebc.ouobIpt-e8p68NztNBngxRplFbz0OtZ1I4xX0s8JTPw+ hash: v1.k794b7964.3e7f0b4280ea7a5cf384476e4aface586231eec249b8838fdc8c23d2296b8f3b.KR42Y7Ds4C-WrfeUR_WjNpuGeU275lvy20riTZz6JVIscenes-app-settings-project--settings-project-product-analytics--light:- hash: v1.k794b7964.3992af9db7065ea06b796a1151165229c36caaa1f65109e84c3bf76369774a8c.MSkawuUPGR3JfomibFguuidjucxIn7SXNN8MJyDeWc8+ hash: v1.k794b7964.cc09c6c8c46f2dd1635982d3a647d3fca8965e41f9b6f3e9f997bd66cd57250b.7JkIJhualVcjPlJcrTluhqpVENR11XjMNhnzCcrBfbwscenes-app-settings-project--settings-project-replay--dark:hash: v1.k794b7964.8ce54ec8a83fd3e878a1bb2d75ef68392487a26f1e0f7de9284561ad71ad8161.Mpfnk_sh9J8RWHJXffqyd_l2OPcxexT5utejEcTANFIscenes-app-settings-project--settings-project-replay--light:diff --git a/frontend/src/scenes/billing/PlanComparison.tsx b/frontend/src/scenes/billing/PlanComparison.tsxindex c7b55ff7260a..adbe489def4d 100644--- a/frontend/src/scenes/billing/PlanComparison.tsx+++ b/frontend/src/scenes/billing/PlanComparison.tsx@@ -112,6 +112,14 @@ const PricingTiers = ({)}+function featuresToCompare(plan?: BillingPlanType): BillingFeatureType[] {+ return (+ plan?.features?.filter(+ (feature) => feature.key !== AvailableFeature.PRODUCT_ANALYTICS_STANDARD_DATA_RETENTION+ ) ?? []+ )+}+export const PlanComparison = ({product,includeAddons = false,@@ -132,6 +140,7 @@ export const PlanComparison = ({return null}const fullyFeaturedPlan = plans[plans.length - 1]+ const comparedFeatures = featuresToCompare(fullyFeaturedPlan)const productAnalyticsPlans = billing?.products?.find((product) => product.type === 'product_analytics')?.plansconst eventsRetentionOf = (plan?: BillingPlanType): BillingFeatureType | undefined =>@@ -282,11 +291,11 @@ export const PlanComparison = ({</h3></th></tr>- {fullyFeaturedPlan?.features?.map((feature, i) => (+ {comparedFeatures.map((feature, i) => (<trkey={`tr-${feature.key}`}className={clsx(- i == fullyFeaturedPlan?.features?.length - 1 &&+ i == comparedFeatures.length - 1 &&!showEventsRetention &&!billing?.has_active_subscription? 'PlanTable__tr__border'@@ -297,7 +306,7 @@ export const PlanComparison = ({className={clsx('PlanTable__th__feature',width && width < 600 && 'PlanTable__th__feature--reduced_padding',- i == fullyFeaturedPlan?.features?.length - 1 &&+ i == comparedFeatures.length - 1 &&!showEventsRetention &&'PlanTable__th__last-feature')}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 860f9e832728..cd0e2269fa12 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -217,6 +217,7 @@ export enum AvailableFeature {SECONDARY_METRICS = 'secondary_metrics',STATISTICAL_ANALYSIS = 'statistical_analysis',PRODUCT_ANALYTICS_DATA_RETENTION = 'product_analytics_data_retention',+ PRODUCT_ANALYTICS_STANDARD_DATA_RETENTION = 'product_analytics_standard_data_retention',DASHBOARDS = 'dashboards',FUNNELS = 'funnels',GRAPHS_TRENDS = 'graphs_trends',diff --git a/products/dashboards/frontend/DashboardRetentionBanner.tsx b/products/dashboards/frontend/DashboardRetentionBanner.tsxindex 1871679b29bd..7c9027032b1e 100644--- a/products/dashboards/frontend/DashboardRetentionBanner.tsx+++ b/products/dashboards/frontend/DashboardRetentionBanner.tsx@@ -8,7 +8,7 @@ import { dataRetentionBannerLogic } from 'products/product_analytics/frontend/inexport const DashboardRetentionBanner = (): JSX.Element | null => {const { showRetentionBanner, retentionPeriodLabel } = useValues(dashboardLogic)- const { retentionBannerAction } = useValues(dataRetentionBannerLogic)+ const { retentionBannerAction, nextDeletionLabel } = useValues(dataRetentionBannerLogic)const { snooze } = useActions(dataRetentionBannerLogic)if (!showRetentionBanner || !retentionPeriodLabel) {@@ -19,6 +19,7 @@ export const DashboardRetentionBanner = (): JSX.Element | null => {<LemonBanner type="warning" className="mt-4 mb-2" onClose={snooze} action={retentionBannerAction ?? undefined}>Some insights on this dashboard have date ranges that go beyond your {retentionPeriodLabel} data retention,so events older than that aren't included.+ {nextDeletionLabel && <span>{` Those events will be deleted starting ${nextDeletionLabel}.`}</span>}</LemonBanner>)}diff --git a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.ts b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.tsindex 7f95de0f1298..aeec0161d35d 100644--- a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.ts+++ b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.ts@@ -12,6 +12,8 @@ import type { OrganizationType } from '~/types'import { eventsRetentionRetrieve } from 'products/product_analytics/frontend/generated/api'import type { EventsRetentionApi } from 'products/product_analytics/frontend/generated/api.schemas'+import { planDeletionDateLabel } from './planDeletionDateLabel'+export interface RetentionBannerAction {children: stringto: string@@ -41,6 +43,7 @@ export interface dataRetentionBannerLogicValues {currentTeamId: number | null // teamLogicaccountAgeEligible: booleanisSnoozed: boolean+ nextDeletionLabel: string | nullretention: EventsRetentionApi | nullretentionApplies: booleanretentionBannerAction: RetentionBannerAction | null@@ -78,6 +81,7 @@ export interface dataRetentionBannerLogicActions {export interface dataRetentionBannerLogicMeta {__keaTypeGenInternalSelectorTypes: {retentionMonths: (retention: EventsRetentionApi | null) => number | null+ nextDeletionLabel: (retention: EventsRetentionApi | null) => string | nullretentionBannerAction: (retention: EventsRetentionApi | null) => RetentionBannerAction | nullretentionEnforced: (retentionMonths: number | null) => booleanretentionPeriodLabel: (retentionMonths: number | null) => string | null@@ -133,6 +137,10 @@ export const dataRetentionBannerLogic = kea<dataRetentionBannerLogicType>([(s) => [s.retention],(retention: EventsRetentionApi | null): number | null => retention?.retention_months ?? null,],+ nextDeletionLabel: [+ (s) => [s.retention],+ (retention: EventsRetentionApi | null): string | null => planDeletionDateLabel(retention),+ ],// Upgrading doesn't help when someone set a window shorter than the plan's, or when the plan is the longest.retentionBannerAction: [(s) => [s.retention],diff --git a/products/product_analytics/frontend/insights/dataRetention/planDeletionDateLabel.test.ts b/products/product_analytics/frontend/insights/dataRetention/planDeletionDateLabel.test.tsnew file mode 100644index 000000000000..512ddb30447a--- /dev/null+++ b/products/product_analytics/frontend/insights/dataRetention/planDeletionDateLabel.test.ts@@ -0,0 +1,33 @@+import type { EventsRetentionApi } from 'products/product_analytics/frontend/generated/api.schemas'++import { planDeletionDateLabel } from './planDeletionDateLabel'++const RETENTION: EventsRetentionApi = {+ retention_months: 12,+ retained_from: '2025-11-03',+ docs_url: 'https://posthog.com/docs/data/events-retention',+ project_retention_months: null,+ next_deletion_on: '2027-02-03',+ next_deletion_before: '2026-02-01',+ scheduled_pass_on: '2027-02-03',+ first_pass_on: '2027-02-03',+ default_period_deletes: true,+ organization_retention_months: null,+ default_retention_months: 12,+ default_is_grandfathered: false,+ plan_retention_months: 12,+ min_retention_months: 1,+ max_retention_months: 12,+ retention_months_choices: [1, 3, 12, 24, 36, 60, 84],+ next_monthly_cleanup_on: '2026-11-03',+}++describe('planDeletionDateLabel', () => {+ it.each([+ ['formats the date of the next deletion', RETENTION, 'February 3, 2027'],+ ['hides the date while no deletion is scheduled', { ...RETENTION, next_deletion_on: null }, null],+ ['hides the date before the retention loads', null, null],+ ])('%s', (_name, retention, expected) => {+ expect(planDeletionDateLabel(retention)).toEqual(expected)+ })+})diff --git a/products/product_analytics/frontend/insights/dataRetention/planDeletionDateLabel.ts b/products/product_analytics/frontend/insights/dataRetention/planDeletionDateLabel.tsnew file mode 100644index 000000000000..8b38f2413f93--- /dev/null+++ b/products/product_analytics/frontend/insights/dataRetention/planDeletionDateLabel.ts@@ -0,0 +1,7 @@+import { dayjs } from 'lib/dayjs'++import type { EventsRetentionApi } from 'products/product_analytics/frontend/generated/api.schemas'++export function planDeletionDateLabel(retention: EventsRetentionApi | null): string | null {+ return retention?.next_deletion_on ? dayjs(retention.next_deletion_on).format('MMMM D, YYYY') : null+}diff --git a/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsx b/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsxindex df89a5322f2e..2ae15184d9a8 100644--- a/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsx+++ b/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsx@@ -10,7 +10,7 @@ import { insightRetentionBannerLogic } from './insightRetentionBannerLogic'export function InsightRetentionBanner({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element | null {const { shouldShowBanner } = useValues(insightRetentionBannerLogic(insightProps))- const { retentionPeriodLabel, retentionBannerAction } = useValues(dataRetentionBannerLogic)+ const { retentionPeriodLabel, retentionBannerAction, nextDeletionLabel } = useValues(dataRetentionBannerLogic)const { snooze } = useActions(dataRetentionBannerLogic)if (!shouldShowBanner || !retentionPeriodLabel) {@@ -21,6 +21,7 @@ export function InsightRetentionBanner({ insightProps }: { insightProps: Insight<LemonBanner type="warning" onClose={snooze} action={retentionBannerAction ?? undefined}>This insight's date range goes beyond your {retentionPeriodLabel} data retention, so events older than thataren't included.+ {nextDeletionLabel && <span>{` Those events will be deleted starting ${nextDeletionLabel}.`}</span>}</LemonBanner>)}diff --git a/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsx b/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsxnew file mode 100644index 000000000000..d416a3bf6324--- /dev/null+++ b/products/product_analytics/frontend/settings/EventsRetentionChangeNote.tsx@@ -0,0 +1,31 @@+import { dayjs } from 'lib/dayjs'++import { RetentionDeletion } from './retentionChangeDeletion'+import { retentionPeriodLabel } from './retentionPeriodLabel'++export interface EventsRetentionChangeNoteProps {+ months: number+ scope: string+ deletion: RetentionDeletion | null+}++function deletionTiming(period: string, { monthly, deletesOn }: RetentionDeletion): string {+ const next = deletesOn ? dayjs(deletesOn).format('MMMM D, YYYY') : null+ if (monthly) {+ return `Deletion isn't instant. A cleanup runs once a month and deletes whole months of events, so some events are kept up to about a month past ${period}.${next ? ` The next cleanup is on ${next}.` : ''}`+ }+ return `Deletion isn't instant. A cleanup every 3 months deletes events past the default period, a whole month at a time, so some events are kept a few months past ${period}. ${next ? `The next one is on ${next}.` : 'The first one is at least 3 months from now.'}`+}++export function EventsRetentionChangeNote({ months, scope, deletion }: EventsRetentionChangeNoteProps): JSX.Element {+ if (!deletion) {+ return <p className="mb-0">Events that were already deleted can't be restored.</p>+ }+ const period = retentionPeriodLabel(months)+ 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>+ <p className="mb-0">{deletionTiming(period, deletion)}</p>+ </div>+ )+}diff --git a/products/product_analytics/frontend/settings/EventsRetentionPeriodSelect.tsx b/products/product_analytics/frontend/settings/EventsRetentionPeriodSelect.tsxnew file mode 100644index 000000000000..fbe1a79f0d27--- /dev/null+++ b/products/product_analytics/frontend/settings/EventsRetentionPeriodSelect.tsx@@ -0,0 +1,93 @@+import { useState } from 'react'++import { LemonButton, LemonDialog, LemonLabel, LemonSelect, LemonTag } from '@posthog/lemon-ui'++import { EventsRetentionChangeNote } from './EventsRetentionChangeNote'+import { EventsRetentionPeriodChoices, eventsRetentionPeriodOptions } from './eventsRetentionPeriodOptions'+import { EventsRetentionSupportPeriodModal } from './EventsRetentionSupportPeriodModal'+import { RetentionPeriods, retentionChangeDeletion } from './retentionChangeDeletion'+import { retentionPeriodLabel } from './retentionPeriodLabel'++export interface EventsRetentionPeriodSelectProps extends RetentionPeriods, EventsRetentionPeriodChoices {+ scope: string+ owner: string+ note: string | JSX.Element+ saving: boolean+ restrictionReason: string | null+ onSave: (months: number | null) => void+}++export function EventsRetentionPeriodSelect(props: EventsRetentionPeriodSelectProps): JSX.Element {+ const { retentionMonths, defaultMonths, choices, scope, owner, note, saving, restrictionReason, onSave, dataAttr } =+ props+ const [changingSupportPeriod, setChangingSupportPeriod] = useState(false)+ const options = eventsRetentionPeriodOptions(props)+ const supportMonths = retentionMonths !== null && !choices.includes(retentionMonths) ? retentionMonths : null++ const confirm = (months: number | null): void => {+ const period = retentionPeriodLabel(months ?? defaultMonths)+ const deletion = retentionChangeDeletion(props, months)+ LemonDialog.open({+ title: `Keep events for ${period}?`,+ maxWidth: '32rem',+ content: <EventsRetentionChangeNote months={months ?? defaultMonths} scope={scope} deletion={deletion} />,+ primaryButton: {+ children: `Keep events for ${period}`,+ status: deletion ? 'danger' : 'default',+ onClick: () => onSave(months),+ 'data-attr': `${dataAttr}-confirm`,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ return (+ <div className="flex flex-col gap-1 max-w-160">+ <LemonLabel>Retention period</LemonLabel>+ {supportMonths === null ? (+ <LemonSelect<number | null>+ value={retentionMonths}+ onChange={confirm}+ options={options}+ loading={saving}+ disabledReason={restrictionReason ?? undefined}+ className="w-80 max-w-full"+ data-attr={`${dataAttr}-select`}+ />+ ) : (+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-semibold">{retentionPeriodLabel(supportMonths)}</span>+ <LemonTag>Set by PostHog support</LemonTag>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setChangingSupportPeriod(true)}+ loading={saving}+ disabledReason={restrictionReason}+ data-attr={`${dataAttr}-change-support-period`}+ >+ Change+ </LemonButton>+ </div>+ )}+ <p className="mb-0 text-xs text-secondary">+ <span>{note}</span>+ {retentionMonths !== null && (+ <span> Older events are deleted once a month, so some are kept up to about a month longer.</span>+ )}+ </p>+ {supportMonths !== null && changingSupportPeriod && (+ <EventsRetentionSupportPeriodModal+ periods={props}+ supportMonths={supportMonths}+ owner={owner}+ scope={scope}+ options={options}+ onSave={onSave}+ onClose={() => setChangingSupportPeriod(false)}+ dataAttr={dataAttr}+ />+ )}+ </div>+ )+}diff --git a/products/product_analytics/frontend/settings/EventsRetentionPlanNote.tsx b/products/product_analytics/frontend/settings/EventsRetentionPlanNote.tsxnew file mode 100644index 000000000000..08f66211a70f--- /dev/null+++ b/products/product_analytics/frontend/settings/EventsRetentionPlanNote.tsx@@ -0,0 +1,57 @@+import { useValues } from 'kea'++import { Link } from '@posthog/lemon-ui'++import { billingLogic } from 'lib/logic/billing/billingLogic'+import { urls } from 'scenes/urls'++import { BillingPlan } from '~/types'++import type { OrganizationEventsRetentionApi } from 'products/product_analytics/frontend/generated/api.schemas'+import { LONGEST_PLAN_RETENTION_MONTHS } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'++import { retentionPeriodLabel } from './retentionPeriodLabel'++export type EventsRetentionPlan = Pick<+ OrganizationEventsRetentionApi,+ 'plan_retention_months' | 'default_retention_months' | 'default_is_grandfathered'+>++const BILLING_PLAN_NAMES: Record<BillingPlan, string> = {+ [BillingPlan.Free]: 'Free',+ [BillingPlan.Paid]: 'Pay-as-you-go',+ [BillingPlan.Teams]: 'Teams',+ [BillingPlan.Boost]: 'Boost',+ [BillingPlan.Scale]: 'Scale',+ [BillingPlan.Enterprise]: 'Enterprise',+}++function planSummary(plan: EventsRetentionPlan, billingPlan: BillingPlan | null): string {+ const yourPlan = billingPlan ? `You're on the ${BILLING_PLAN_NAMES[billingPlan]} plan, which` : 'Your plan'+ const longest = retentionPeriodLabel(plan.plan_retention_months)+ const byDefault = retentionPeriodLabel(plan.default_retention_months)+ if (plan.default_is_grandfathered || plan.default_retention_months < plan.plan_retention_months) {+ return `${yourPlan} allows up to ${longest} for custom events retention policies. The default retention period for this plan is ${byDefault}.`+ }+ return `${yourPlan} has ${longest} of events data retention.`+}++export function EventsRetentionPlanNote({ plan }: { plan: EventsRetentionPlan }): JSX.Element {+ const { billingPlan } = useValues(billingLogic)++ return (+ <p+ className="max-w-160 mb-4 rounded border bg-surface-primary px-3 py-2 text-secondary"+ data-attr="events-retention-plan-note"+ >+ <span>{planSummary(plan, billingPlan)}</span>+ {plan.plan_retention_months < LONGEST_PLAN_RETENTION_MONTHS && (+ <>+ {' '}+ Need longer data retention? Head over to our{' '}+ <Link to={urls.organizationBilling()}>billing page</Link> to upgrade.+ </>+ )}+ </p>+ )+}diff --git a/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx b/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsxindex 34c33c112e20..40921ecff7e2 100644--- a/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx+++ b/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx@@ -1,6 +1,8 @@import { Meta, StoryObj } from '@storybook/react'import { mswDecorator } from '~/mocks/browser'+import { billingJson } from '~/mocks/fixtures/_billing'+import { BillingPlan } from '~/types'import type {EventsRetentionApi,@@ -19,56 +21,91 @@ const meta: Meta = {export default metatype Story = StoryObj-const retentionMocks = (- organizationMonths: number | null,- projectMonths: number | null-): ReturnType<typeof mswDecorator> => {+interface RetentionMockOptions {+ organizationMonths?: number | null+ projectMonths?: number | null+ planMonths?: number+ grandfathered?: boolean+ billingPlan?: BillingPlan+}++const retentionMocks = ({+ organizationMonths = null,+ projectMonths = null,+ planMonths = 36,+ grandfathered = false,+ billingPlan = BillingPlan.Boost,+}: RetentionMockOptions): ReturnType<typeof mswDecorator> => {+ const defaultMonths = grandfathered ? planMonths : Math.min(planMonths, 24)const organization: OrganizationEventsRetentionApi = {organization_retention_months: organizationMonths,- default_retention_months: 36,- default_is_grandfathered: true,- plan_retention_months: 36,+ default_retention_months: defaultMonths,+ default_is_grandfathered: grandfathered,+ plan_retention_months: planMonths,min_retention_months: 1,- max_retention_months: 36,+ max_retention_months: planMonths,retention_months_choices: [1, 3, 12, 24, 36, 60, 84],next_monthly_cleanup_on: '2026-11-03',}const project: EventsRetentionApi = {...organization,- retention_months: projectMonths ?? organizationMonths ?? 36,+ retention_months: Math.min(planMonths, projectMonths ?? organizationMonths ?? defaultMonths),retained_from: '2024-11-01',docs_url: 'https://posthog.com/docs/data/events-retention',project_retention_months: projectMonths,next_deletion_on: null,next_deletion_before: null,- scheduled_pass_on: null,+ scheduled_pass_on: '2027-02-03',first_pass_on: '2027-02-03',- default_period_deletes: false,+ default_period_deletes: true,}return mswDecorator({get: {'/api/projects/:team_id/events_retention/': project,'/api/organizations/:organization_id/events_retention_setting/': organization,+ '/api/billing/': { ...billingJson, billing_plan: billingPlan },},})}-export const OrganizationWithoutWindow: Story = {+export const OrganizationWithoutPeriod: Story = {+ render: () => <OrganizationEventsRetentionSetting />,+ decorators: [retentionMocks({})],+}++export const OrganizationWithPeriod: Story = {+ render: () => <OrganizationEventsRetentionSetting />,+ decorators: [retentionMocks({ organizationMonths: 12 })],+}++export const OrganizationOnGrandfatheredPlan: Story = {render: () => <OrganizationEventsRetentionSetting />,- decorators: [retentionMocks(null, null)],+ decorators: [retentionMocks({ planMonths: 84, grandfathered: true, billingPlan: BillingPlan.Paid })],}-export const OrganizationWithWindow: Story = {+export const OrganizationOnFreePlan: Story = {render: () => <OrganizationEventsRetentionSetting />,- decorators: [retentionMocks(24, null)],+ decorators: [retentionMocks({ planMonths: 12, billingPlan: BillingPlan.Free })],+}++export const ProjectUsingOrganizationPeriod: Story = {+ render: () => <ProjectEventsRetentionSetting />,+ decorators: [retentionMocks({ organizationMonths: 12 })],+}++export const ProjectWithOwnPeriod: Story = {+ render: () => <ProjectEventsRetentionSetting />,+ decorators: [retentionMocks({ organizationMonths: 24, projectMonths: 12 })],}-export const ProjectUsingOrganizationWindow: Story = {+export const ProjectWithOwnPeriodAbovePlan: Story = {render: () => <ProjectEventsRetentionSetting />,- decorators: [retentionMocks(24, null)],+ decorators: [retentionMocks({ planMonths: 24, projectMonths: 36, billingPlan: BillingPlan.Paid })],+ parameters: { testOptions: { snapshotBrowsers: [] } },}-export const ProjectWithOwnWindow: Story = {+export const ProjectWithSupportPeriod: Story = {render: () => <ProjectEventsRetentionSetting />,- decorators: [retentionMocks(24, 12)],+ decorators: [retentionMocks({ organizationMonths: 24, projectMonths: 18 })],+ parameters: { testOptions: { snapshotBrowsers: [] } },}diff --git a/products/product_analytics/frontend/settings/EventsRetentionSupportPeriodModal.tsx b/products/product_analytics/frontend/settings/EventsRetentionSupportPeriodModal.tsxnew file mode 100644index 000000000000..3970d0f89e0b--- /dev/null+++ b/products/product_analytics/frontend/settings/EventsRetentionSupportPeriodModal.tsx@@ -0,0 +1,78 @@+import { useState } from 'react'++import { LemonButton, LemonLabel, LemonModal, LemonSelect, LemonSelectOptions } from '@posthog/lemon-ui'++import { EventsRetentionChangeNote } from './EventsRetentionChangeNote'+import { RetentionPeriods, retentionChangeDeletion } from './retentionChangeDeletion'+import { retentionPeriodLabel } from './retentionPeriodLabel'++export interface EventsRetentionSupportPeriodModalProps {+ periods: RetentionPeriods+ supportMonths: number+ owner: string+ scope: string+ options: LemonSelectOptions<number | null>+ onSave: (months: number | null) => void+ onClose: () => void+ dataAttr: string+}++export function EventsRetentionSupportPeriodModal({+ periods,+ supportMonths,+ owner,+ scope,+ options,+ onSave,+ onClose,+ dataAttr,+}: EventsRetentionSupportPeriodModalProps): JSX.Element {+ const [months, setMonths] = useState<number | null>(null)+ const supportPeriod = retentionPeriodLabel(supportMonths)+ const keptMonths = months ?? periods.defaultMonths+ const deletion = retentionChangeDeletion({ ...periods, retentionMonths: supportMonths }, months)++ return (+ <LemonModal+ isOpen+ onClose={onClose}+ title="Change the period PostHog support set?"+ maxWidth="32rem"+ footer={+ <>+ <LemonButton type="secondary" onClick={onClose}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ status={deletion ? 'danger' : 'default'}+ onClick={() => {+ onSave(months)+ onClose()+ }}+ data-attr={`${dataAttr}-confirm`}+ >+ {`Keep events for ${retentionPeriodLabel(keptMonths)}`}+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <p className="mb-0">+ {`PostHog support set ${owner} to keep events for ${supportPeriod}. If you change it, you can only pick one of the standard periods, and you'll need to contact support to get ${supportPeriod} back.`}+ </p>+ <div className="flex flex-col gap-1">+ <LemonLabel>New retention period</LemonLabel>+ <LemonSelect<number | null>+ value={months}+ onChange={setMonths}+ options={options}+ className="w-80 max-w-full"+ data-attr={`${dataAttr}-support-select`}+ />+ </div>+ <EventsRetentionChangeNote months={keptMonths} scope={scope} deletion={deletion} />+ </div>+ </LemonModal>+ )+}diff --git a/products/product_analytics/frontend/settings/EventsRetentionWindowForm.tsx b/products/product_analytics/frontend/settings/EventsRetentionWindowForm.tsxdeleted file mode 100644index 865b88a0056e..000000000000--- a/products/product_analytics/frontend/settings/EventsRetentionWindowForm.tsx+++ /dev/null@@ -1,144 +0,0 @@-import { useEffect, useState } from 'react'--import { LemonBanner, LemonButton, LemonDialog, LemonInput, Link } from '@posthog/lemon-ui'--import { urls } from 'scenes/urls'--import { LONGEST_PLAN_RETENTION_MONTHS } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'--export interface EventsRetentionWindowFormProps {- retentionMonths: number | null- minMonths: number- maxMonths: number- planMonths: number- /** Who keeps events for the chosen window, as the start of a sentence, e.g. "This project". */- keptBy: string- /** What happens when the window is removed. */- removedDescription: string- saving: boolean- restrictionReason: string | null- onSave: (retentionMonths: number | null) => void- dataAttr: string-}--function draftMonthsProblem(- draftMonths: number | undefined,- minMonths: number,- maxMonths: number,- retentionMonths: number | null-): string | null {- if (draftMonths === undefined || !Number.isInteger(draftMonths)) {- return 'Enter a whole number of months'- }- if (draftMonths < minMonths || draftMonths > maxMonths) {- return `Choose between ${minMonths} and ${maxMonths} months`- }- if (draftMonths === retentionMonths) {- return 'No changes to save'- }- return null-}--export function EventsRetentionWindowForm({- retentionMonths,- minMonths,- maxMonths,- planMonths,- keptBy,- removedDescription,- saving,- restrictionReason,- onSave,- dataAttr,-}: EventsRetentionWindowFormProps): JSX.Element {- const [draftMonths, setDraftMonths] = useState<number | undefined>(retentionMonths ?? undefined)-- useEffect(() => {- setDraftMonths(retentionMonths ?? undefined)- }, [retentionMonths])-- const saveDisabledReason =- restrictionReason ?? draftMonthsProblem(draftMonths, minMonths, maxMonths, retentionMonths)-- const confirmSave = (): void => {- if (draftMonths === undefined) {- return- }- LemonDialog.open({- title: `Delete events older than ${draftMonths} months?`,- description: `${keptBy} keeps events for ${draftMonths} months. Older events are deleted at the next monthly cleanup and can't be restored.`,- primaryButton: {- children: 'Delete older events',- status: 'danger',- onClick: () => onSave(draftMonths),- 'data-attr': `${dataAttr}-confirm`,- },- secondaryButton: { children: 'Cancel' },- })- }-- const confirmRemove = (): void => {- LemonDialog.open({- title: 'Remove this window?',- description: removedDescription,- primaryButton: {- children: 'Remove window',- onClick: () => onSave(null),- 'data-attr': `${dataAttr}-remove-confirm`,- },- secondaryButton: { children: 'Cancel' },- })- }-- return (- <div>- <LemonBanner type="warning" className="max-w-160 mb-4">- Events older than this window are deleted at the next monthly cleanup. Deleted events can't be restored.- </LemonBanner>- <div className="flex flex-wrap items-center gap-2">- <LemonInput- type="number"- min={minMonths}- max={maxMonths}- value={draftMonths}- onChange={setDraftMonths}- onPressEnter={() => !saveDisabledReason && confirmSave()}- placeholder="Not set"- suffix={<span className="text-secondary">months</span>}- disabled={!!restrictionReason || saving}- className="w-40"- data-attr={`${dataAttr}-input`}- />- <LemonButton- type="primary"- status="danger"- onClick={confirmSave}- loading={saving}- disabledReason={saveDisabledReason}- data-attr={`${dataAttr}-save`}- >- Save- </LemonButton>- {retentionMonths !== null && (- <LemonButton- type="secondary"- onClick={confirmRemove}- disabledReason={restrictionReason ?? (saving ? 'Saving...' : null)}- data-attr={`${dataAttr}-remove`}- >- Remove window- </LemonButton>- )}- </div>- <p className="mt-2 mb-0 text-sm text-secondary">- You can choose between {minMonths} and {maxMonths} months.- {maxMonths === planMonths && planMonths < LONGEST_PLAN_RETENTION_MONTHS && (- <>- {' '}- Need a longer window? <Link to={urls.organizationBilling()}>Upgrade your plan</Link>.- </>- )}- </p>- </div>- )-}diff --git a/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsx b/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsxindex 235df7834d7e..6aec1df50239 100644--- a/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsx+++ b/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsx@@ -5,8 +5,9 @@ import { Link } from '@posthog/lemon-ui'import { useRestrictedArea } from 'lib/components/RestrictedArea'import { OrganizationMembershipLevel } from 'lib/constants'+import { EventsRetentionPeriodSelect } from './EventsRetentionPeriodSelect'+import { EventsRetentionPlanNote } from './EventsRetentionPlanNote'import { eventsRetentionSettingsLogic } from './eventsRetentionSettingsLogic'-import { EventsRetentionWindowForm } from './EventsRetentionWindowForm'export function OrganizationEventsRetentionSetting(): JSX.Element | null {const { projectRetention, organizationRetention, organizationRetentionLoading } =@@ -18,25 +19,29 @@ export function OrganizationEventsRetentionSetting(): JSX.Element | null {return null}- const planMonths = organizationRetention.plan_retention_months-return (<div>- <p className="max-w-160 text-sm text-secondary mb-4">- Choose how long projects in this organization keep events. A project can set its own window instead.{' '}- {organizationRetention.organization_retention_months === null &&- `No window is set, so projects keep events for your plan's window of ${planMonths} months. `}+ <p className="max-w-160 text-sm text-secondary mb-2">+ Choose how long projects in this organization keep events. A project can set its own period instead.{' '}<Link to={projectRetention.docs_url} target="_blank">Learn more</Link></p>- <EventsRetentionWindowForm+ <EventsRetentionPlanNote plan={organizationRetention} />+ <EventsRetentionPeriodSelectretentionMonths={organizationRetention.organization_retention_months}+ defaultLabel="Default"+ defaultMonths={organizationRetention.default_retention_months}+ monthlyDefaultMonths={null}+ choices={organizationRetention.retention_months_choices}minMonths={organizationRetention.min_retention_months}maxMonths={organizationRetention.max_retention_months}- planMonths={planMonths}- keptBy="Every project without its own window"- removedDescription={`Projects without their own window will keep events for your plan's window of ${planMonths} months.`}+ planMonths={organizationRetention.plan_retention_months}+ nextMonthlyCleanupOn={organizationRetention.next_monthly_cleanup_on}+ passSchedule={null}+ scope="Events in projects without their own period"+ owner="this organization"+ note="Projects without their own period use this."saving={organizationRetentionLoading}restrictionReason={restrictionReason}onSave={updateOrganizationRetention}diff --git a/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsx b/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsxindex 31c1605777fb..7087bcbbdf96 100644--- a/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsx+++ b/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsx@@ -6,8 +6,10 @@ import { useRestrictedArea } from 'lib/components/RestrictedArea'import { OrganizationMembershipLevel } from 'lib/constants'import { urls } from 'scenes/urls'+import { EventsRetentionPeriodSelect } from './EventsRetentionPeriodSelect'+import { EventsRetentionPlanNote } from './EventsRetentionPlanNote'import { eventsRetentionSettingsLogic } from './eventsRetentionSettingsLogic'-import { EventsRetentionWindowForm } from './EventsRetentionWindowForm'+import { retentionPeriodLabel } from './retentionPeriodLabel'export function ProjectEventsRetentionSetting(): JSX.Element | null {const { projectRetention, projectRetentionLoading } = useValues(eventsRetentionSettingsLogic)@@ -18,35 +20,46 @@ export function ProjectEventsRetentionSetting(): JSX.Element | null {return null}- const organizationMonths = projectRetention.organization_retention_months- const planMonths = projectRetention.plan_retention_months- const fallback =- organizationMonths !== null- ? `the organization's window of ${organizationMonths} months`- : `your plan's window of ${planMonths} months`+ const organizationMonths =+ projectRetention.organization_retention_months === null+ ? null+ : Math.min(projectRetention.organization_retention_months, projectRetention.plan_retention_months)+ const defaultMonths = organizationMonths ?? projectRetention.default_retention_monthsreturn (<div>- <p className="max-w-160 text-sm text-secondary mb-4">- Choose how long this project keeps events. This replaces the window set in{' '}- <Link to={urls.settings('organization-details', 'organization-events-retention')}>- organization settings- </Link>- . {projectRetention.project_retention_months === null && `This project uses ${fallback}. `}+ <p className="max-w-160 text-sm text-secondary mb-2">+ Choose how long this project keeps events.{' '}<Link to={projectRetention.docs_url} target="_blank">Learn more</Link></p>- <EventsRetentionWindowForm+ <EventsRetentionPlanNote plan={projectRetention} />+ <EventsRetentionPeriodSelectretentionMonths={projectRetention.project_retention_months}+ defaultLabel="Organization default"+ defaultMonths={defaultMonths}+ monthlyDefaultMonths={projectRetention.organization_retention_months}+ choices={projectRetention.retention_months_choices}minMonths={projectRetention.min_retention_months}maxMonths={projectRetention.max_retention_months}- planMonths={planMonths}- keptBy="This project"- removedDescription={- organizationMonths !== null- ? `This project will use ${fallback}. Older events are deleted at the next monthly cleanup and can't be restored.`- : `This project will keep events for ${fallback}.`+ planMonths={projectRetention.plan_retention_months}+ nextMonthlyCleanupOn={projectRetention.next_monthly_cleanup_on}+ passSchedule={projectRetention}+ scope="Events in this project"+ owner="this project"+ note={+ projectRetention.project_retention_months === null ? (+ <>+ <span>{`This project uses the organization's events retention. You can change it in `}</span>+ <Link to={urls.settings('organization-details', 'organization-events-retention')}>+ organization settings+ </Link>+ <span>.</span>+ </>+ ) : (+ `This overrides the organization default of ${retentionPeriodLabel(defaultMonths)}.`+ )}saving={projectRetentionLoading}restrictionReason={restrictionReason}diff --git a/products/product_analytics/frontend/settings/eventsRetentionPeriodOptions.tsx b/products/product_analytics/frontend/settings/eventsRetentionPeriodOptions.tsxnew file mode 100644index 000000000000..adb72d8601d1--- /dev/null+++ b/products/product_analytics/frontend/settings/eventsRetentionPeriodOptions.tsx@@ -0,0 +1,60 @@+import { IconLock } from '@posthog/icons'+import { LemonSelectOption, LemonSelectSection } from '@posthog/lemon-ui'++import { retentionPeriodLabel } from './retentionPeriodLabel'++export interface EventsRetentionPeriodChoices {+ defaultLabel: string+ defaultMonths: number+ choices: readonly number[]+ minMonths: number+ maxMonths: number+ planMonths: number+ dataAttr: string+}++function choiceOption(+ months: number,+ { minMonths, maxMonths, planMonths, dataAttr }: EventsRetentionPeriodChoices+): LemonSelectOption<number | null> {+ const option = { value: months, label: retentionPeriodLabel(months), 'data-attr': `${dataAttr}-option-${months}` }+ if (months > planMonths) {+ return {+ ...option,+ labelInMenu: (+ <span className="flex flex-1 items-center justify-between gap-2">+ <span className="flex items-center gap-2">+ <IconLock />+ {option.label}+ </span>+ <span className="text-xs text-secondary">Upgrade</span>+ </span>+ ),+ disabledReason: `Your plan keeps events for up to ${retentionPeriodLabel(planMonths)}. Upgrade your plan to keep them longer.`,+ }+ }+ if (months < minMonths || months > maxMonths) {+ return {+ ...option,+ disabledReason: `This organization can keep events for ${retentionPeriodLabel(minMonths)} to ${retentionPeriodLabel(maxMonths)}. Contact PostHog support to change this.`,+ }+ }+ return option+}++export function eventsRetentionPeriodOptions(+ choices: EventsRetentionPeriodChoices+): LemonSelectSection<number | null>[] {+ return [+ {+ options: [+ {+ value: null,+ label: `${choices.defaultLabel} (${retentionPeriodLabel(choices.defaultMonths)})`,+ 'data-attr': `${choices.dataAttr}-option-default`,+ },+ ],+ },+ { options: choices.choices.map((months) => choiceOption(months, choices)) },+ ]+}diff --git a/products/product_analytics/frontend/settings/nextPassOn.test.ts b/products/product_analytics/frontend/settings/nextPassOn.test.tsnew file mode 100644index 000000000000..5ede8560b7d3--- /dev/null+++ b/products/product_analytics/frontend/settings/nextPassOn.test.ts@@ -0,0 +1,22 @@+import { EventsPassSchedule, nextPassOn } from './nextPassOn'++const SCHEDULED: EventsPassSchedule = {+ scheduled_pass_on: '2026-12-03',+ first_pass_on: '2027-02-03',+ default_period_deletes: true,+}++describe('nextPassOn', () => {+ it.each([+ ['waits at least 3 months for a shorter period', SCHEDULED, '2027-02-03'],+ ['keeps a later scheduled pass', { ...SCHEDULED, scheduled_pass_on: '2027-05-03' }, '2027-05-03'],+ ['knows no date before admission', { ...SCHEDULED, scheduled_pass_on: null }, null],+ [+ 'deletes nothing when the cleanup does not enforce the default',+ { ...SCHEDULED, default_period_deletes: false },+ null,+ ],+ ])('%s', (_name, schedule, expected) => {+ expect(nextPassOn(schedule)).toEqual(expected)+ })+})diff --git a/products/product_analytics/frontend/settings/nextPassOn.ts b/products/product_analytics/frontend/settings/nextPassOn.tsnew file mode 100644index 000000000000..9b12a618fd6f--- /dev/null+++ b/products/product_analytics/frontend/settings/nextPassOn.ts@@ -0,0 +1,13 @@+import type { EventsRetentionApi } from 'products/product_analytics/frontend/generated/api.schemas'++export type EventsPassSchedule = Pick<+ EventsRetentionApi,+ 'scheduled_pass_on' | 'first_pass_on' | 'default_period_deletes'+>++export function nextPassOn(schedule: EventsPassSchedule): string | null {+ if (!schedule.default_period_deletes || schedule.scheduled_pass_on === null) {+ return null+ }+ return schedule.first_pass_on > schedule.scheduled_pass_on ? schedule.first_pass_on : schedule.scheduled_pass_on+}diff --git a/products/product_analytics/frontend/settings/retentionChangeDeletion.test.ts b/products/product_analytics/frontend/settings/retentionChangeDeletion.test.tsnew file mode 100644index 000000000000..ff6fc009a3f9--- /dev/null+++ b/products/product_analytics/frontend/settings/retentionChangeDeletion.test.ts@@ -0,0 +1,51 @@+import { RetentionPeriods, retentionChangeDeletion } from './retentionChangeDeletion'++const DOWNGRADED: RetentionPeriods = {+ retentionMonths: 36,+ defaultMonths: 12,+ monthlyDefaultMonths: 18,+ planMonths: 12,+ nextMonthlyCleanupOn: '2026-12-03',+ passSchedule: null,+}++const ON_PLAN_DEFAULT: RetentionPeriods = {+ retentionMonths: 36,+ defaultMonths: 24,+ monthlyDefaultMonths: null,+ planMonths: 84,+ nextMonthlyCleanupOn: '2026-12-03',+ passSchedule: { scheduled_pass_on: '2027-02-03', first_pass_on: '2027-02-03', default_period_deletes: true },+}++describe('retentionChangeDeletion', () => {+ it.each([+ ['a shorter organization period past the plan', DOWNGRADED, null, { monthly: true, deletesOn: '2026-12-03' }],+ ['a longer organization period past the plan', { ...DOWNGRADED, monthlyDefaultMonths: 40 }, null, null],+ [+ 'a shorter default the cleanup does not enforce',+ {+ ...ON_PLAN_DEFAULT,+ passSchedule: { scheduled_pass_on: null, first_pass_on: '2027-02-03', default_period_deletes: false },+ },+ null,+ null,+ ],+ ['a shorter plan default', ON_PLAN_DEFAULT, null, { monthly: false, deletesOn: '2027-02-03' }],+ [+ 'a shorter own period',+ { ...DOWNGRADED, retentionMonths: 24 },+ 12,+ { monthly: true, deletesOn: '2026-12-03' },+ ],+ ['a longer own period', { ...DOWNGRADED, retentionMonths: 12 }, 24, null],+ [+ 'any period while the plan default applies',+ { ...ON_PLAN_DEFAULT, retentionMonths: null },+ 84,+ { monthly: true, deletesOn: '2026-12-03' },+ ],+ ])('%s', (_name, periods, months, expected) => {+ expect(retentionChangeDeletion(periods, months)).toEqual(expected)+ })+})diff --git a/products/product_analytics/frontend/settings/retentionChangeDeletion.ts b/products/product_analytics/frontend/settings/retentionChangeDeletion.tsnew file mode 100644index 000000000000..42761c4836e5--- /dev/null+++ b/products/product_analytics/frontend/settings/retentionChangeDeletion.ts@@ -0,0 +1,42 @@+import { EventsPassSchedule, nextPassOn } from './nextPassOn'++export interface RetentionPeriods {+ retentionMonths: number | null+ defaultMonths: number+ monthlyDefaultMonths: number | null+ planMonths: number+ nextMonthlyCleanupOn: string+ passSchedule: EventsPassSchedule | null+}++export interface RetentionDeletion {+ monthly: boolean+ deletesOn: string | null+}++function deletesKeptEvents(periods: RetentionPeriods, months: number | null): boolean {+ const { retentionMonths, monthlyDefaultMonths } = periods+ if (retentionMonths === null) {+ return months !== null && (monthlyDefaultMonths === null || months < monthlyDefaultMonths)+ }+ if (months !== null) {+ return months < retentionMonths+ }+ if (monthlyDefaultMonths !== null) {+ return monthlyDefaultMonths < retentionMonths+ }+ return (+ (periods.passSchedule?.default_period_deletes ?? true) &&+ periods.defaultMonths < Math.min(periods.planMonths, retentionMonths)+ )+}++export function retentionChangeDeletion(periods: RetentionPeriods, months: number | null): RetentionDeletion | null {+ if (!deletesKeptEvents(periods, months)) {+ return null+ }+ if (months !== null || periods.monthlyDefaultMonths !== null) {+ return { monthly: true, deletesOn: periods.nextMonthlyCleanupOn }+ }+ return { monthly: false, deletesOn: periods.passSchedule && nextPassOn(periods.passSchedule) }+}diff --git a/products/product_analytics/frontend/settings/retentionPeriodLabel.ts b/products/product_analytics/frontend/settings/retentionPeriodLabel.tsnew file mode 100644index 000000000000..c3d13b2b1973--- /dev/null+++ b/products/product_analytics/frontend/settings/retentionPeriodLabel.ts@@ -0,0 +1,5 @@+import { pluralize } from 'lib/utils/strings'++export function retentionPeriodLabel(months: number): string {+ return months % 12 === 0 ? pluralize(months / 12, 'year') : pluralize(months, 'month')+}