: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(growth): add organization product push campaigns (#67968)
Rafael Audibert4a5b48d93627
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 15311dc99e2b..9ca1bbbd8aa0 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -153,6 +153,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"ErrorTrackingIssueAssignment","StreamlitAppVersion","FeatureFlagEvaluationContext",+ "ProductPushCampaign","Run","RunSnapshot","TicketAssignment",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5a433db1e4eb..8ef1cadba311 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1272,6 +1272,14 @@ snapshots:hash: v1.k794b7964.0e8104bc157a94e4a189c153f1cdd32e631e5dfafb409c5748e6444112e6b083.40iqRsl1MTWxx72-j944X6yykg4h5eT36x8UDa6EajEcomponents-mcp-use-case-card--surveys-create--light:hash: v1.k794b7964.b661e4e398c7e4d4ddc8147808d77a5469d58ef0b03f5e249a8f3e8e3292033e.chYHGb_myBwyHq4I_2Jyj59FUmcFRaTfloWtxB-ZWS8+ components-navpanelproductpush--all-products--dark:+ hash: v1.k794b7964.70e51ca304e26d9c0778eafa3031983d1906d49e62ee377d0792ae013bff2e19.P1NqL-7BkCpdNq_GR7GJmAdWw-9h8eaXk4QL1nc47rU+ components-navpanelproductpush--all-products--light:+ hash: v1.k794b7964.ffbda961735b84627929955561160d2e7a0a00c0a91fc5342deef8ee6e7ecfaa.urmsqUvrer7Bym4XyXABFVJOhC12OT_PiZH58fIFXJw+ components-navpanelproductpush--default-fallback--dark:+ hash: v1.k794b7964.73c20ea721009efba63d0b347a37dbef0ca34d3d19724c6f5158aadbc138f20e.Aih-CDdZmGHnefWI5954Zgk2lpSJXuVKgluWjrNUOqg+ components-navpanelproductpush--default-fallback--light:+ hash: v1.k794b7964.c21ed9ee3902f9b0f242e207c5d9d15353b4927f6153d251a35421048c602544.VYc6ozOtCMTbvtt4k9YpZURkEostfdIBq1-WLe6i1WYcomponents-networkrequest-navigationitem--all-slow--dark:hash: v1.k794b7964.d09d9acbf8cb33a45a26cc9fd6e238dd97fa80b5b38c244dab95cd662d085c42.iV22pgH-xBLY-79NVxnPiKvZQ3vbBvZ7uthloHKd9Sccomponents-networkrequest-navigationitem--all-slow--light:@@ -6845,37 +6853,37 @@ snapshots:scenes-app-settings-user--settings-user-reminders-modal--light:hash: v1.k794b7964.fbcf3f0f69a5b43c28ea7537ce6f1aab3c21e70f9c2cbb6fdfef4546dadba86c.yYIPurSofuNP1kZXYzNBOa3YU5Zy7VLaSegvGrNZ8Mwscenes-app-sidepanels--side-panel-access-control--dark:- hash: v1.k794b7964.88250100e04267ede8805595c6f22f2d95a0aaa60e20e44811523e3732207490.Ae02U70H59fZ-IEfUh8DCvpFgnsJq2JQwOvCGm9vfeU+ hash: v1.k794b7964.75d9a0a3295e5934ade86ea12368ce74cf49bb5ce5c09192537e5750585dcd71.50LYrEMMiQ1o7eIwNS3GjeSdu_jZYAYwksuWoubI-78scenes-app-sidepanels--side-panel-access-control--light:- hash: v1.k794b7964.a0ad43e75cdadac6f118834e445020fd92beb5a0f192bb45fb42c115adc1a579.VRePz4T76290rQSTGlnKhxvXKrA3RF2-_bQ-Q4VMUgk+ hash: v1.k794b7964.e3a4bb21aef674776f6fdf5c87c11008e2cb7584739bc0f74cadf12bafeca954.dB07ACMnoVuyXrf4tlu7YdwsQg0EmuDsR-34tD_V3bwscenes-app-sidepanels--side-panel-activity--dark:- hash: v1.k794b7964.72809d69b9c87b9f207731819ffd68d5fb41222ef15ce45d3962813a52903a79.wNhQ1q3YSpkPckdhWIW6j_8P3O36qM8On_aXfS0eyII+ hash: v1.k794b7964.8b040446695f50e30e55253fa564611abfc8ebb5255d6ef7ef120397129f037f.Qy8aPwN-EIIdZJHUHCSMcqGdPwBziRo0_YeBT8Vhnaoscenes-app-sidepanels--side-panel-activity--light:- hash: v1.k794b7964.ba1cc6d82083761bf380a2cac131eef70658e144dffe1423138df28c459f7898.tyxiSZwd5zLqZ1mt7b7Z7sngxlMdPGg33Fg_wNDjjaI+ hash: v1.k794b7964.6628bf586917018da09ef0fd4dcf677f2ef7613230b6b9da4108b540e405dfb1.jU_GqmGFbCaVdt3zTZmJK24fKZrjayujaHVFPJDMV9Uscenes-app-sidepanels--side-panel-discussion--dark:- hash: v1.k794b7964.3b3d81bfe11b3d3a1664223a288efccce470c46b80b888745273bbbe1abcee6d.3OG0xRWhpRiMlgM9d-QW9vR8ywQ0Dd1PkzGsLJjF4So+ hash: v1.k794b7964.1fb1a487b07b89e6d81b45cd5a1a9f1e141b9e1e5bac4679dd31606b2e8740b0.19viq6ZN3jDAi-LMIUXealK3LugR8uKWBL77XLRfD8cscenes-app-sidepanels--side-panel-discussion--light:- hash: v1.k794b7964.5c1a88ffbff38e617678d731799ac255ef9b8c7cdcdc6e2bb7556bc5c77abef6.VPn4zSEwouXv9KMHMqayYUiEsN6fahXJg62o9SA6pok+ hash: v1.k794b7964.7031c913ef187797a2ed6d87e542a50625e2c1d742ba7a1aa018872ebaaeb127.2uVIlBsVBP_jiL-T1CWQ6kek85z7DLQrOf3LpUiOt-Uscenes-app-sidepanels--side-panel-exports--dark:- hash: v1.k794b7964.1d49297911e102204f059fe2646e07932b1931c88b29e1526d899be27de2ca3d.QPPN-yE4wNDo9zBLi4-J-qdmdBY-QvSKz_HATZ_iH2c+ hash: v1.k794b7964.d31c7483918a80345d3a6087ab08fdc9957861510be767bf2f2310c8ea24bdc6.2KYblhJKrNwzgQnf5hhqpb2QYRosA7JT5LhJ5FSHfaAscenes-app-sidepanels--side-panel-exports--light:- hash: v1.k794b7964.7814e7adaecda26ecd372925b1f810654f00da84df5eb518f5fad7d4dd166b43.GQ33_WkijqpsifxhNf1MoUFyW-d3gG2L7USW9SSvRNE+ hash: v1.k794b7964.4e0558544e54b663466e3cc5471af58787f80e424c1362f19ce241e409fe6896.fn3ZlFCF1Y09Dahd7ELeTIEp-yj6tATjVkPZP0B90tUscenes-app-sidepanels--side-panel-info--dark:- hash: v1.k794b7964.88250100e04267ede8805595c6f22f2d95a0aaa60e20e44811523e3732207490.Zy0nHVEwf0NTRSFz7ILY8eqGOII804-cT24WmOMEaRs+ hash: v1.k794b7964.75d9a0a3295e5934ade86ea12368ce74cf49bb5ce5c09192537e5750585dcd71.8XUhNuYljbI7mM9GGoyop7uV6QlNr1_1GespCPInHQ4scenes-app-sidepanels--side-panel-info--light:- hash: v1.k794b7964.a0ad43e75cdadac6f118834e445020fd92beb5a0f192bb45fb42c115adc1a579.q64ZnocW3c9SQTNQ3geI0kA6oSrh_Pm7pDoQjKjf0M8+ hash: v1.k794b7964.e3a4bb21aef674776f6fdf5c87c11008e2cb7584739bc0f74cadf12bafeca954.TGBluQvOkUZGYgiUG53zuepsY-3nSNdNagFJ5XjqRz0scenes-app-sidepanels--side-panel-max--dark:- hash: v1.k794b7964.88250100e04267ede8805595c6f22f2d95a0aaa60e20e44811523e3732207490.o3LbT9ylSrYjqiLU7z_rMu83X-Ze04Ah8FP_qMkyUa4+ hash: v1.k794b7964.75d9a0a3295e5934ade86ea12368ce74cf49bb5ce5c09192537e5750585dcd71.t9FIPCyPLXcst70dTav9enQ3EXWJvOTuXIafPZ8BxUoscenes-app-sidepanels--side-panel-max--light:- hash: v1.k794b7964.a0ad43e75cdadac6f118834e445020fd92beb5a0f192bb45fb42c115adc1a579.aQv_ta21jrcwzkq8oXNPQZ6s7OMqLHc2bdM6TaImE5k+ hash: v1.k794b7964.8982b205095b40e925775e82021f737fcb8dfb066ab2acdebeb747bcf3fc2441.0CaNwy_S3WhrqI5I3hWqwtcxJMU892f2FhNchtDhJCwscenes-app-sidepanels--side-panel-notebooks--dark:- hash: v1.k794b7964.1c5091c6f6fa621862ce948f2b396f9b758a0f609211978364e303b196ec055c.HsNS5PfDrICWkVeHf-0MkaSW8yU83bwpswXrV81VJ1k+ hash: v1.k794b7964.87e60bb3963a3568f4cd1db1ffe8535187546aa633e72a28029175baf98701d0.6k-fL8y6dAuTID8XRqdlMhXBWKSb85TpzLeIedt5PHsscenes-app-sidepanels--side-panel-notebooks--light:- hash: v1.k794b7964.fc99a9703f4448adca13c515de201f7e10f7889b2a762b0f8382b86b6380b3e9.bCTF_uEE2Qn3eLGmYTEDW_eGWxkljFBD8N609H43mxY+ hash: v1.k794b7964.15b1430a1c9ab5e3d223bd3940722ab202ae0f8a9df08c595463d16594d22577.Me9gU_Xd1v6Fz3o2kw4sFv-cxDLSK9Z8umPpGuV6_L8scenes-app-sidepanels--side-panel-support--dark:- hash: v1.k794b7964.78bf90213c45284408c6fd1fc3a3093e362bc4e82e7bcc283232a02fb9ec1ec8.GYp1r9Pvtko0j7ANRLK_6p5WBurEuNA60IyVg_I48OM+ hash: v1.k794b7964.220b0da2325a5c600b217d9e06d9ec871e14b5ddaf57f7d63203a8f762fa42bd.7ROM87CPLFyenH0MF2b5iQ6qxAQdMJvf8dETokiYrOMscenes-app-sidepanels--side-panel-support--light:- hash: v1.k794b7964.34974d5d44fa48fc84cb826dc4e230b553f6d8e6cb8f6638e9df0e9748753d28.2-YDnrybyJhvD2dITBKjk3fqllFlnLt-3eigDTL1cLk+ hash: v1.k794b7964.00d74aa61dfc093adbe4517776e510a47cdf75cd7f5931eeab5fb34f8ccfd560.nUFvZsCTBH-oNUaRqLdU0DuOG4x332lN7_IREb8K-n8scenes-app-subscriptions-subscription-delivery-history--empty--dark:hash: v1.k794b7964.267363ce3a0453be58b96ef2c00446ae4aaf5ed42b02472c495b3c468f25e18f.PmJd-8ou979ieSrNpJQ2DxtM8Tnqs7jtvU6k-2rpr2wscenes-app-subscriptions-subscription-delivery-history--empty--light:@@ -7085,17 +7093,17 @@ snapshots:scenes-app-visual-review-run--tracking-only-master-run--light:hash: v1.k794b7964.82f2750059b1ef9ab2adb777da603d4d0985b7213235780f24377be11e601a5e.BdVEZ3jDXINsbZgssAvaGfjq_qmGcGOqm2AhdvSYmXgscenes-app-web-analytics--web-analytics-dashboard--dark:- hash: v1.k794b7964.db5c649a7d7397caed01efbf2706740078cd45c035caa366127db204a22a7dce.oilG9ZO_9AaaI-D_0sahiYY3JObuTOh_x3MUdGKLnu8+ hash: v1.k794b7964.cbd196cdbf3b1bb63a5b595bf3664935ddbeea9864205775f3142d6c1fe8f9fe.rpGGWHZqpZrlVvvv0xueufnpBj8loVpVaTW5fRaQHtIscenes-app-web-analytics--web-analytics-dashboard--light:- hash: v1.k794b7964.dcb2299a665c5f29edef68824d3b25d465fe6834d48202438dd0b1fef6929675.Qs9XVYadzTuSabYYMCidpNznr1_EKUg-kgUjZXAgG0E+ hash: v1.k794b7964.ba3ae25b65f6bdb5543544347e3dfda70829eddb82efe1399afe6a5d99c0d1ed.K4QHEV19HxB-2gJDTvB2KGA_7WqnG2hlIlZz3MA6C7cscenes-app-web-analytics--web-analytics-dashboard-loading--dark:- hash: v1.k794b7964.13c191791b54d3883701293c658ccf42a25ed2265230ea3e8c92848089f1ea83.wzAikTVVVF7ZR1jPHFB2zzzKAlzdKWhiQfW415XaBFU+ hash: v1.k794b7964.b013feb2079b7ea61e8729fa6dba5eaa004649c6605d055853f0e19c5b364436.EBImZsjSWcoLJsL83AAxzuqFX6hk_vu7QXICQPun8q0scenes-app-web-analytics--web-analytics-dashboard-loading--light:- hash: v1.k794b7964.9f201392ec044e8032dc1e189fb286853eee0b5950368e6b70f1d86fac43cdbf.XCVsdz7izCJPEpx-CeOfwsRd9MobcHQsLG-8EUDdRFU+ hash: v1.k794b7964.3e03b4395a4ecfa030b723ba7c0096738911ab6ded9aef857fb5b8a3d1732f13.qL5yYKkJ8OZQns8BF3wXY-bAjQklSsupd2D6Q3N1nVMscenes-app-web-analytics--web-analytics-dashboard-metric-cards--dark:- hash: v1.k794b7964.2f82a6d3707c43a7696fec402dcacb4c1a94841043c5c006e424ff4296f442d2.r61bC6tV63Hr-x73p1nRLjTwSck8JL18YTsLNTFOzp8+ hash: v1.k794b7964.31877d6979aba7f0b50bab1fdc625f1f9734e09dd3ac267a7610350f182dd8a4.-DQx-qsS_w-sQucWQkDddaqLhbhvm9xLlYoky3AUSgEscenes-app-web-analytics--web-analytics-dashboard-metric-cards--light:- hash: v1.k794b7964.d950c582749f43dd0831930feb7c3d7c68daebb74c03b51a1e44947c92da3cfc.Wd2PfF5bxRbj3pmaBJ9WDwDdFWrVv7I9ZT9mfSdH2CA+ hash: v1.k794b7964.883ee01bd37750a07a948987f6913617492ecd5f12f40f29eef0b2eb89f11ed0.m_z4rlGAD6V9gQkIxWFBs7_9bGI7TfYCxkFVq-TmAHYscenes-app-web-analytics-achievements--daily-only-arm--dark:hash: v1.k794b7964.8f024a521e113d8101749768f8d4f49d8dcac1365f43d9b2038c6df0021bac6a.BYx467NAatau4dzb13PnZCTODi-yUho-Vhm_JdtCY9wscenes-app-web-analytics-achievements--daily-only-arm--light:diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsxindex 0e8e07cd18b1..ba97fc64c77a 100644--- a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx@@ -1,53 +1,25 @@-import { BindLogic, useActions, useValues } from 'kea'-import posthog from 'posthog-js'-import { useEffect } from 'react'+import { useValues } from 'kea'-import { IconX } from '@posthog/icons'-import { Link } from '@posthog/lemon-ui'--import { LemonButton } from 'lib/lemon-ui/LemonButton'import { getFeatureFlagPayload } from 'lib/logic/featureFlagLogic'-import { addProductIntent } from 'lib/utils/product-intents'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { userLogic } from 'scenes/userLogic'import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'-import { getTreeItemsProducts } from '~/products'-import {- FileSystemImport,- ProductIntentContext,- ProductKey,- UserProductListItem,- UserProductListReason,-} from '~/queries/schema/schema-general'-import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'+import { CampaignPayload, isCampaignPayload } from './navPanelAdShared'import { navPanelAdvertisementRecommendedLogic } from './navPanelAdvertisementRecommendedLogic'--interface CampaignPayload {- campaign: string- text: string- emoji: string- emojiLabel: string- title: string-}--function isCampaignPayload(value: unknown): value is CampaignPayload {- return (- typeof value === 'object' &&- value !== null &&- typeof (value as CampaignPayload).campaign === 'string' &&- typeof (value as CampaignPayload).text === 'string' &&- typeof (value as CampaignPayload).emoji === 'string' &&- typeof (value as CampaignPayload).emojiLabel === 'string' &&- typeof (value as CampaignPayload).title === 'string'- )-}+import { NavPanelCampaignAd } from './NavPanelCampaignAd'+import { NavPanelProductPushAd } from './NavPanelProductPushAd'+import { navPanelProductPushLogic } from './navPanelProductPushLogic'+import { NavPanelRecommendationAd } from './NavPanelRecommendationAd'export function NavPanelAdvertisement(): JSX.Element | null {const logic = navPanelAdvertisementRecommendedLogic()const { oldestRecommendedProduct } = useValues(logic)+ const { activeCampaign } = useValues(navPanelProductPushLogic)const { isLayoutNavCollapsed } = useValues(panelLayoutLogic)const { isCloudOrDev } = useValues(preflightLogic)+ const { user } = useValues(userLogic)const campaignFlagPayload = getFeatureFlagPayload('nav-panel-campaign') as CampaignPayload | undefined@@ -57,178 +29,18 @@ export function NavPanelAdvertisement(): JSX.Element | null {// Campaign flag payload takes priority over product recommendations, but campaigns promote cloud features so are not shown on hobbyif (isCloudOrDev && isCampaignPayload(campaignFlagPayload)) {- return <NavPanelCampaignContent campaign={campaignFlagPayload} />- }-- if (!oldestRecommendedProduct) {- return null+ return <NavPanelCampaignAd campaign={campaignFlagPayload} />}- return <NavPanelAdvertisementContent recommendedProduct={oldestRecommendedProduct} />-}--function NavPanelCampaignContent({ campaign }: { campaign: CampaignPayload }): JSX.Element | null {- const logicProps = { campaign: `campaign-${campaign.campaign}` }- const logic = navPanelAdvertisementLogic(logicProps)- const { hidden } = useValues(logic)-- useEffect(() => {- if (!hidden) {- posthog.capture('nav panel campaign shown', { campaign: campaign.campaign })- }- }, [campaign.campaign, hidden])-- if (hidden) {- return null+ // The org-wide product push campaign, driven by the growth backend. Respects the+ // user's "no product suggestions" setting.+ if (isCloudOrDev && activeCampaign && user?.allow_sidebar_suggestions !== false) {+ return <NavPanelProductPushAd campaign={activeCampaign} />}- return (- <BindLogic logic={navPanelAdvertisementLogic} props={logicProps}>- <Content- emoji={campaign.emoji}- emojiLabel={campaign.emojiLabel}- title={campaign.title}- text={campaign.text}- onClose={() => {- posthog.capture('nav panel campaign dismissed', {- campaign: campaign.campaign,- })- }}- />- </BindLogic>- )-}--function NavPanelAdvertisementContent({- recommendedProduct,-}: {- recommendedProduct: UserProductListItem-}): JSX.Element | null {- const allProducts = getTreeItemsProducts()- const productInfo: FileSystemImport | undefined = allProducts.find(- (p: FileSystemImport) => p.path === recommendedProduct.product_path- )-- const logicProps = { campaign: recommendedProduct.product_path }- const logic = navPanelAdvertisementLogic(logicProps)- const { hidden } = useValues(logic)-- useEffect(() => {- if (!hidden && productInfo) {- posthog.capture('nav panel advertisement shown', {- product_path: recommendedProduct.product_path,- product_id: recommendedProduct.id,- })- }- }, [recommendedProduct.product_path, recommendedProduct.id, productInfo, hidden])-- const reasonText = getReasonText(recommendedProduct)- if (hidden || !productInfo || !reasonText) {+ if (!oldestRecommendedProduct) {return null}- return (- <div className="w-full">- <Link- to={productInfo.href}- className="text-primary"- onClick={() => {- posthog.capture('nav panel advertisement clicked', {- product_path: recommendedProduct.product_path,- product_id: recommendedProduct.id,- })- if (productInfo.intents && productInfo.intents.length > 0) {- const productKey = productInfo.intents[0]- if (productKey in ProductKey) {- addProductIntent({- product_type: productKey as ProductKey,- intent_context: ProductIntentContext.NAV_PANEL_ADVERTISEMENT_CLICKED,- metadata: { product_path: recommendedProduct.product_path },- })- }- }- }}- >- <BindLogic logic={navPanelAdvertisementLogic} props={logicProps}>- <Content- emoji="✨"- emojiLabel="sparkles"- title={productInfo.displayLabel ?? productInfo.path}- text={getReasonText(recommendedProduct) ?? ''}- onClose={() => {- posthog.capture('nav panel advertisement dismissed', {- product_path: recommendedProduct.product_path,- product_id: recommendedProduct.id,- })- }}- />- </BindLogic>- </Link>- </div>- )-}--function Content({- emoji,- emojiLabel,- title,- text,- onClose,-}: {- emoji: string- emojiLabel: string- title: string- text: string- onClose?: () => void-}): JSX.Element {- const { hideAdvertisement } = useActions(navPanelAdvertisementLogic)-- return (- <div className="border rounded-sm bg-primary text-xs *:flex *:gap-2 *:px-2 *:py-1">- <div className="flex justify-between">- <div className="flex items-center gap-2">- <strong>- <span role="img" aria-label={emojiLabel}>- {emoji}- </span>{' '}- {title}- </strong>- </div>- <LemonButton- icon={<IconX className="text-muted m-1" />}- tooltip="Dismiss"- tooltipPlacement="right"- size="xxsmall"- onClick={(e) => {- e.preventDefault()- e.stopPropagation()-- onClose?.()-- hideAdvertisement()- }}- noPadding- />- </div>-- <div className="flex flex-col gap-1">- <p className="mb-0" dangerouslySetInnerHTML={{ __html: text }} />- </div>- </div>- )-}--const getReasonText = (product: UserProductListItem): string | null => {- if (product.reason_text) {- return product.reason_text- }-- switch (product.reason) {- case UserProductListReason.SALES_LED:- return "We've added this product to your sidebar because we believe you'd benefit from it! Your TAM will reach out to help you learn more about it."- case UserProductListReason.NEW_PRODUCT:- return "We've just released this new product. Based on your usage, we believe you'll like it. Give it a try!"- }-- return null+ return <NavPanelRecommendationAd recommendedProduct={oldestRecommendedProduct} />}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelCampaignAd.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelCampaignAd.tsxnew file mode 100644index 000000000000..5a8570e4bfc0--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelCampaignAd.tsx@@ -0,0 +1,38 @@+import { BindLogic, useValues } from 'kea'+import posthog from 'posthog-js'+import { useEffect } from 'react'++import { CampaignPayload, AdvertisementCard } from './navPanelAdShared'+import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'++export function NavPanelCampaignAd({ campaign }: { campaign: CampaignPayload }): JSX.Element | null {+ const logicProps = { campaign: `campaign-${campaign.campaign}` }+ const logic = navPanelAdvertisementLogic(logicProps)+ const { hidden } = useValues(logic)++ useEffect(() => {+ if (!hidden) {+ posthog.capture('nav panel campaign shown', { campaign: campaign.campaign })+ }+ }, [campaign.campaign, hidden])++ if (hidden) {+ return null+ }++ return (+ <BindLogic logic={navPanelAdvertisementLogic} props={logicProps}>+ <AdvertisementCard+ emoji={campaign.emoji}+ emojiLabel={campaign.emojiLabel}+ title={campaign.title}+ text={campaign.text}+ onClose={() => {+ posthog.capture('nav panel campaign dismissed', {+ campaign: campaign.campaign,+ })+ }}+ />+ </BindLogic>+ )+}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelProductPushAd.stories.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelProductPushAd.stories.tsxnew file mode 100644index 000000000000..f9b772aa0a4f--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelProductPushAd.stories.tsx@@ -0,0 +1,70 @@+import type { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'++import { AdvertisementCard, ProductPushDisplay } from './navPanelAdShared'+import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'+import { DEFAULT_PRODUCT_PUSH_DISPLAY, PRODUCT_PUSH_DISPLAY } from './navPanelProductPushDisplay'++const meta = {+ title: 'Components/NavPanelProductPush',+ parameters: { layout: 'padded' },+} satisfies Meta<typeof AdvertisementCard>++export default meta+type Story = StoryObj<typeof meta>++/**+ * A card for a product push campaign. The campaign is the product key, the title is the product name, and the display is the product display.+ */+const PushCard = ({+ campaign,+ title,+ display,+}: {+ campaign: string+ title: string+ display: ProductPushDisplay+}): JSX.Element => (+ // The push card renders inside the (narrow) sidebar, so mirror that width here.+ <div className="w-[232px]">+ <div className="mb-1 font-mono text-xs text-muted">{campaign}</div>+ <BindLogic logic={navPanelAdvertisementLogic} props={{ campaign: `story-${campaign}` }}>+ <AdvertisementCard title={title} text={display.tagline} hero={display} />+ </BindLogic>+ </div>+)++// One card per pushable product, so a reviewer can eyeball every hoggie / brand color / tagline at once.+export const AllProducts: Story = {+ render: (): JSX.Element => {+ // 'session_replay' -> 'Session replay'. The live component titles the card with the product's+ // catalog label; a story has no catalog to resolve against, so humanize the key instead.+ const humanizeProductKey = (productKey: string): string => {+ const spaced = productKey.replace(/_/g, ' ')+ const sentence = spaced.charAt(0).toUpperCase() + spaced.slice(1)+ return sentence.replace(/^Llm\b/, 'LLM')+ }++ return (+ <div className="flex flex-wrap items-start gap-4">+ {(Object.entries(PRODUCT_PUSH_DISPLAY) as [string, ProductPushDisplay][]).map(+ ([productKey, display]) => (+ <PushCard+ key={productKey}+ campaign={productKey}+ title={humanizeProductKey(productKey)}+ display={display}+ />+ )+ )}+ </div>+ )+ },+}++// What a product key with no bespoke entry falls back to (e.g. a TAM-scheduled push of an unlisted product).+export const DefaultFallback: Story = {+ render: (): JSX.Element => (+ <PushCard campaign="default_fallback" title="Any other product" display={DEFAULT_PRODUCT_PUSH_DISPLAY} />+ ),+}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelProductPushAd.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelProductPushAd.tsxnew file mode 100644index 000000000000..29f17aace123--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelProductPushAd.tsx@@ -0,0 +1,34 @@+import { BindLogic, useActions, useValues } from 'kea'++import { Link } from '@posthog/lemon-ui'++import type { ProductPushCampaignApi } from 'products/growth/frontend/generated/api.schemas'++import { AdvertisementCard } from './navPanelAdShared'+import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'+import { navPanelProductPushAdLogic } from './navPanelProductPushAdLogic'++export function NavPanelProductPushAd({ campaign }: { campaign: ProductPushCampaignApi }): JSX.Element | null {+ const logic = navPanelProductPushAdLogic({ campaign })+ const { productInfo, display, shouldRender } = useValues(logic)+ const { reportAdClicked, reportAdDismissed } = useActions(logic)++ if (!shouldRender || !productInfo) {+ return null+ }++ return (+ <div className="w-full">+ <Link to={productInfo.href} className="text-primary" onClick={() => reportAdClicked()}>+ <BindLogic logic={navPanelAdvertisementLogic} props={{ campaign: `product-push-${campaign.id}` }}>+ <AdvertisementCard+ title={productInfo.displayLabel ?? productInfo.path}+ text={campaign.reason_text || display.tagline}+ hero={display}+ onClose={() => reportAdDismissed()}+ />+ </BindLogic>+ </Link>+ </div>+ )+}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelRecommendationAd.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelRecommendationAd.tsxnew file mode 100644index 000000000000..d41c9f0703ad--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelRecommendationAd.tsx@@ -0,0 +1,103 @@+import { BindLogic, useValues } from 'kea'+import posthog from 'posthog-js'+import { useEffect } from 'react'++import { Link } from '@posthog/lemon-ui'++import { addProductIntent } from 'lib/utils/product-intents'++import { getTreeItemsProducts } from '~/products'+import {+ FileSystemImport,+ ProductIntentContext,+ ProductKey,+ UserProductListItem,+ UserProductListReason,+} from '~/queries/schema/schema-general'++import { AdvertisementCard } from './navPanelAdShared'+import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'++const getReasonText = (product: UserProductListItem): string | null => {+ if (product.reason_text) {+ return product.reason_text+ }++ switch (product.reason) {+ case UserProductListReason.SALES_LED:+ return "We've added this product to your sidebar because we believe you'd benefit from it! Your TAM will reach out to help you learn more about it."+ case UserProductListReason.NEW_PRODUCT:+ return "We've just released this new product. Based on your usage, we believe you'll like it. Give it a try!"+ }++ return null+}++export function NavPanelRecommendationAd({+ recommendedProduct,+}: {+ recommendedProduct: UserProductListItem+}): JSX.Element | null {+ const allProducts = getTreeItemsProducts()+ const productInfo: FileSystemImport | undefined = allProducts.find(+ (p: FileSystemImport) => p.path === recommendedProduct.product_path+ )++ const logicProps = { campaign: recommendedProduct.product_path }+ const logic = navPanelAdvertisementLogic(logicProps)+ const { hidden } = useValues(logic)++ useEffect(() => {+ if (!hidden && productInfo) {+ posthog.capture('nav panel advertisement shown', {+ product_path: recommendedProduct.product_path,+ product_id: recommendedProduct.id,+ })+ }+ }, [recommendedProduct.product_path, recommendedProduct.id, productInfo, hidden])++ const reasonText = getReasonText(recommendedProduct)+ if (hidden || !productInfo || !reasonText) {+ return null+ }++ return (+ <div className="w-full">+ <Link+ to={productInfo.href}+ className="text-primary"+ onClick={() => {+ posthog.capture('nav panel advertisement clicked', {+ product_path: recommendedProduct.product_path,+ product_id: recommendedProduct.id,+ })+ if (productInfo.intents && productInfo.intents.length > 0) {+ const productKey = productInfo.intents[0]+ if (productKey in ProductKey) {+ addProductIntent({+ product_type: productKey as ProductKey,+ intent_context: ProductIntentContext.NAV_PANEL_ADVERTISEMENT_CLICKED,+ metadata: { product_path: recommendedProduct.product_path },+ })+ }+ }+ }}+ >+ <BindLogic logic={navPanelAdvertisementLogic} props={logicProps}>+ <AdvertisementCard+ emoji="✨"+ emojiLabel="sparkles"+ title={productInfo.displayLabel ?? productInfo.path}+ text={getReasonText(recommendedProduct) ?? ''}+ onClose={() => {+ posthog.capture('nav panel advertisement dismissed', {+ product_path: recommendedProduct.product_path,+ product_id: recommendedProduct.id,+ })+ }}+ />+ </BindLogic>+ </Link>+ </div>+ )+}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx b/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsxnew file mode 100644index 000000000000..31e26e6f1e21--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdShared.tsx@@ -0,0 +1,174 @@+import { useActions } from 'kea'++import type { SvgAssetComponent } from '@posthog/brand'+import { IconX } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'++import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'++export interface CampaignPayload {+ campaign: string+ text: string+ emoji: string+ emojiLabel: string+ title: string+}++export function isCampaignPayload(value: unknown): value is CampaignPayload {+ return (+ typeof value === 'object' &&+ value !== null &&+ typeof (value as CampaignPayload).campaign === 'string' &&+ typeof (value as CampaignPayload).text === 'string' &&+ typeof (value as CampaignPayload).emoji === 'string' &&+ typeof (value as CampaignPayload).emojiLabel === 'string' &&+ typeof (value as CampaignPayload).title === 'string'+ )+}++export interface ProductPushDisplay {+ /** Hoggie illustration shown in the promo card's hero image */+ Hoggie: SvgAssetComponent+ /** Product brand color driving the hero's geometric background */+ accentColor: string+ /** Default promo copy, used when the campaign has no custom reason text */+ tagline: string+}++// Playful scattered shapes behind the hoggie, tinted white over the product's brand color+function GeometricPattern(): JSX.Element {+ return (+ <svg+ className="absolute inset-0 h-full w-full text-white"+ viewBox="0 0 232 96"+ preserveAspectRatio="xMidYMid slice"+ aria-hidden="true"+ >+ <circle cx="26" cy="22" r="11" fill="currentColor" opacity="0.25" />+ <circle cx="204" cy="66" r="17" fill="none" stroke="currentColor" strokeWidth="3" opacity="0.3" />+ <rect+ x="176"+ y="10"+ width="15"+ height="15"+ rx="2"+ transform="rotate(18 183 17)"+ fill="currentColor"+ opacity="0.2"+ />+ <polygon points="64,10 75,30 53,30" fill="currentColor" opacity="0.3" />+ <path+ d="M8 62 l7 -8 7 8 7 -8 7 8"+ fill="none"+ stroke="currentColor"+ strokeWidth="2.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ opacity="0.35"+ />+ <circle cx="118" cy="14" r="4" fill="currentColor" opacity="0.35" />+ <path+ d="M148 78 h12 M154 72 v12"+ stroke="currentColor"+ strokeWidth="3"+ strokeLinecap="round"+ opacity="0.3"+ />+ <circle cx="52" cy="78" r="6" fill="none" stroke="currentColor" strokeWidth="2.5" opacity="0.25" />+ <rect+ x="96"+ y="70"+ width="10"+ height="10"+ transform="rotate(-12 101 75)"+ fill="currentColor"+ opacity="0.18"+ />+ <polygon+ points="206,18 214,32 198,32"+ fill="none"+ stroke="currentColor"+ strokeWidth="2.5"+ strokeLinejoin="round"+ opacity="0.3"+ />+ </svg>+ )+}++export function AdvertisementCard({+ emoji,+ emojiLabel,+ title,+ text,+ hero,+ onClose,+}: {+ emoji?: string+ emojiLabel?: string+ title: string+ text: string+ hero?: ProductPushDisplay+ onClose?: () => void+}): JSX.Element {+ const { hideAdvertisement } = useActions(navPanelAdvertisementLogic)++ const dismissButton = (+ <LemonButton+ icon={<IconX className={hero ? 'text-white' : 'text-muted'} />}+ tooltip="Dismiss"+ tooltipPlacement="right"+ size="xxsmall"+ className={hero ? 'bg-black/20 hover:bg-black/30' : undefined}+ onClick={(e) => {+ e.preventDefault()+ e.stopPropagation()++ onClose?.()++ hideAdvertisement()+ }}+ noPadding+ />+ )++ return (+ <div className="overflow-hidden rounded border bg-surface-primary text-xs shadow-sm transition-shadow hover:shadow-md">+ {hero ? (+ <>+ <div+ className="relative flex h-24 items-center justify-center"+ style={{ backgroundColor: hero.accentColor }}+ >+ <GeometricPattern />+ <hero.Hoggie className="relative h-20 w-auto" aria-hidden="true" />+ <div className="absolute inset-x-0 bottom-0 h-10 bg-gradient-to-b from-transparent to-surface-primary" />+ <div className="absolute top-1 right-1">{dismissButton}</div>+ </div>+ <div className="flex flex-col gap-1 px-2 pt-0.5 pb-2">+ <strong className="text-sm leading-tight">{title}</strong>+ <p className="mb-0 text-secondary">{text}</p>+ </div>+ </>+ ) : (+ <div className="flex flex-col gap-1 px-2 py-1.5">+ <div className="flex items-start justify-between gap-2">+ <strong>+ {emoji ? (+ <>+ <span role="img" aria-label={emojiLabel}>+ {emoji}+ </span>{' '}+ </>+ ) : null}+ {title}+ </strong>+ {dismissButton}+ </div>+ <p className="mb-0 text-secondary">{text}</p>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.ts b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.tsnew file mode 100644index 000000000000..e5447cc61f88--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.ts@@ -0,0 +1,95 @@+import { actions, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import posthog from 'posthog-js'++import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { addProductIntent } from 'lib/utils/product-intents'++import { getTreeItemsProducts } from '~/products'+import { FileSystemImport, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'++import type { ProductPushCampaignApi } from 'products/growth/frontend/generated/api.schemas'++import type { ProductPushDisplay } from './navPanelAdShared'+import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'+import type { navPanelProductPushAdLogicType } from './navPanelProductPushAdLogicType'+import { getProductPushDisplay } from './navPanelProductPushDisplay'++export type NavPanelProductPushAdLogicProps = {+ campaign: ProductPushCampaignApi+}++// The dismiss state lives in the shared advertisement logic (its keyed instance also backs the+// card's dismiss button), so key it the same way here to read the same `hidden` flag.+const dismissKey = (campaign: ProductPushCampaignApi): string => `product-push-${campaign.id}`++export const navPanelProductPushAdLogic = kea<navPanelProductPushAdLogicType>([+ path(['lib', 'components', 'NavPanelAdvertisement', 'navPanelProductPushAdLogic']),+ props({} as NavPanelProductPushAdLogicProps),+ key(({ campaign }) => campaign.id),+ connect((props: NavPanelProductPushAdLogicProps) => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ navPanelAdvertisementLogic({ campaign: dismissKey(props.campaign) }),+ ['hidden'],+ ],+ })),+ actions({+ reportAdShown: true,+ reportAdClicked: true,+ reportAdDismissed: true,+ }),+ selectors({+ productInfo: [+ () => [(_, props) => props.campaign],+ (campaign: ProductPushCampaignApi): FileSystemImport | undefined =>+ getTreeItemsProducts().find((p: FileSystemImport) => p.path === campaign.product_path),+ ],+ display: [+ () => [(_, props) => props.campaign],+ (campaign: ProductPushCampaignApi): ProductPushDisplay => getProductPushDisplay(campaign.product_key),+ ],+ // Never advertise a product this user can't open (mirrors the sidebar's flag filtering)+ flagGated: [+ (s) => [s.productInfo, s.featureFlags],+ (productInfo, featureFlags): boolean =>+ !!productInfo?.flag && !(featureFlags as Record<string, boolean>)[productInfo.flag],+ ],+ shouldRender: [+ (s) => [s.hidden, s.productInfo, s.flagGated],+ (hidden, productInfo, flagGated): boolean => !hidden && !!productInfo && !flagGated,+ ],+ }),+ listeners(({ props }) => ({+ reportAdShown: () => {+ posthog.capture('nav panel product push shown', {+ campaign_id: props.campaign.id,+ product_key: props.campaign.product_key,+ })+ },+ reportAdClicked: () => {+ posthog.capture('nav panel product push clicked', {+ campaign_id: props.campaign.id,+ product_key: props.campaign.product_key,+ })+ if (Object.values(ProductKey).includes(props.campaign.product_key as ProductKey)) {+ addProductIntent({+ product_type: props.campaign.product_key as ProductKey,+ intent_context: ProductIntentContext.NAV_PANEL_ADVERTISEMENT_CLICKED,+ metadata: { campaign_id: props.campaign.id },+ })+ }+ },+ reportAdDismissed: () => {+ posthog.capture('nav panel product push dismissed', {+ campaign_id: props.campaign.id,+ product_key: props.campaign.product_key,+ })+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.shouldRender) {+ actions.reportAdShown()+ }+ }),+])diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushDisplay.ts b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushDisplay.tsnew file mode 100644index 000000000000..e3b6bbb04f62--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushDisplay.ts@@ -0,0 +1,115 @@+import {+ HedgehogChartHog,+ HedgehogCodeBubble,+ HedgehogCursorHog,+ HedgehogDirector,+ HedgehogExperiment,+ HedgehogJudge,+ HedgehogMegaphone,+ HedgehogNoirHog,+ HedgehogPanic,+ HedgehogPhoneCall,+ HedgehogPuzzle,+ HedgehogRoboHog,+ HedgehogTrafficController,+ HedgehogWizardHog,+ HedgehogWorkflows,+} from '@posthog/brand/hoggies'++import { ProductKey } from '~/queries/schema/schema-general'++import type { ProductPushDisplay } from './navPanelAdShared'++export const DEFAULT_PRODUCT_PUSH_DISPLAY: ProductPushDisplay = {+ Hoggie: HedgehogMegaphone,+ accentColor: 'var(--color-accent)',+ tagline:+ "We think your organization would get a lot out of this product - it works with the data you're already sending. Give it a try!",+}++// One entry per pushable product (see BLESSED_PRODUCT_ORDER / FALLBACK_PRODUCT_ORDER in+// products/growth/backend/product_push/selection.py). Products missing here fall back to+// DEFAULT_PRODUCT_PUSH_DISPLAY, so TAM-scheduled pushes of unlisted products still render.+export const PRODUCT_PUSH_DISPLAY: Partial<Record<ProductKey, ProductPushDisplay>> = {+ [ProductKey.PRODUCT_ANALYTICS]: {+ Hoggie: HedgehogChartHog,+ accentColor: 'var(--color-product-product-analytics-light)',+ tagline:+ 'Insights, funnels, trends, and retention - understand exactly what users do in your product, with the events you already send.',+ },+ [ProductKey.WEB_ANALYTICS]: {+ Hoggie: HedgehogCursorHog,+ accentColor: 'var(--color-product-web-analytics-light)',+ tagline:+ 'Visitors, pageviews, and conversions on one simple dashboard. Like GA, without the pain - and no extra setup, ready for you to use.',+ },+ [ProductKey.SESSION_REPLAY]: {+ Hoggie: HedgehogDirector,+ accentColor: 'var(--color-product-session-replay-light)',+ tagline:+ 'Lights, camera, action - watch real users move through your product and see exactly where they get stuck.',+ },+ [ProductKey.ERROR_TRACKING]: {+ Hoggie: HedgehogPanic,+ accentColor: 'var(--color-product-error-tracking-light)',+ tagline:+ 'Catch exceptions before your users tweet about them - errors grouped, triaged, and linked to the sessions that hit them.',+ },+ [ProductKey.FEATURE_FLAGS]: {+ Hoggie: HedgehogTrafficController,+ accentColor: 'var(--color-product-feature-flags-light)',+ tagline: 'Ship to 1% before you ship to everyone. Roll out, target, and roll back - no redeploys needed.',+ },+ [ProductKey.EXPERIMENTS]: {+ Hoggie: HedgehogExperiment,+ accentColor: 'var(--color-product-experiments-light)',+ tagline: 'Stop debating, start testing. Run A/B tests on real users and let the data settle the argument.',+ },+ [ProductKey.CONVERSATIONS]: {+ Hoggie: HedgehogPhoneCall,+ accentColor: 'var(--color-product-support-light)',+ tagline:+ 'Talk to users right inside your product, with their session and event history next to every conversation.',+ },+ [ProductKey.DATA_WAREHOUSE]: {+ Hoggie: HedgehogCodeBubble,+ accentColor: 'var(--color-product-data-warehouse-light)',+ tagline:+ 'Query everything with SQL - your product events plus warehouse sources like Stripe, HubSpot, and Postgres.',+ },+ [ProductKey.AI_OBSERVABILITY]: {+ Hoggie: HedgehogRoboHog,+ accentColor: 'var(--color-product-llm-analytics-light)',+ tagline:+ "Traces, costs, and latency for every LLM call - know what your AI is doing, and what it's costing you.",+ },+ [ProductKey.LLM_CLUSTERS]: {+ Hoggie: HedgehogPuzzle,+ accentColor: 'var(--color-product-llm-clusters-light)',+ tagline: 'Thousands of AI conversations, automatically grouped into patterns you can actually act on.',+ },+ [ProductKey.LLM_EVALUATIONS]: {+ Hoggie: HedgehogJudge,+ accentColor: 'var(--color-product-llm-evaluations-light)',+ tagline: 'Grade your LLM outputs at scale and catch regressions before your users do.',+ },+ [ProductKey.LLM_PROMPTS]: {+ Hoggie: HedgehogWizardHog,+ accentColor: 'var(--color-product-llm-prompts-light)',+ tagline: 'Version, test, and ship prompt changes without redeploying your app. A little magic, fully tracked.',+ },+ [ProductKey.LOGS]: {+ Hoggie: HedgehogNoirHog,+ accentColor: 'var(--color-product-logs-light)',+ tagline: 'Search every log line alongside your product data - no mystery goes unsolved.',+ },+ [ProductKey.WORKFLOWS]: {+ Hoggie: HedgehogWorkflows,+ accentColor: 'var(--color-product-workflows-light)',+ tagline: 'Automate messages and actions triggered by what users actually do in your product.',+ },+}++export function getProductPushDisplay(productKey: string): ProductPushDisplay {+ return PRODUCT_PUSH_DISPLAY[productKey as ProductKey] ?? DEFAULT_PRODUCT_PUSH_DISPLAY+}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushLogic.test.ts b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushLogic.test.tsnew file mode 100644index 000000000000..05a54505fe05--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushLogic.test.ts@@ -0,0 +1,65 @@+import { expectLogic } from 'kea-test-utils'++import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { initKeaTests } from '~/test/init'++import * as growthApi from 'products/growth/frontend/generated/api'+import type { ProductPushCampaignApi } from 'products/growth/frontend/generated/api.schemas'++import { navPanelProductPushLogic } from './navPanelProductPushLogic'++const MOCK_CAMPAIGN: ProductPushCampaignApi = {+ id: '0197c2a2-0000-0000-0000-000000000000',+ product_key: 'session_replay',+ product_path: 'Session replay',+ reason_text: 'Watch real sessions.',+ started_at: '2026-07-01T00:00:00Z',+ ends_at: '2026-07-31T00:00:00Z',+}++describe('navPanelProductPushLogic', () => {+ let logic: ReturnType<typeof navPanelProductPushLogic.build>++ beforeEach(async () => {+ initKeaTests()+ // The loader is gated on isCloudOrDev, so wait for cloud-ness to be known+ // (the default preflight fixture has is_debug=true → isCloudOrDev=true)+ await expectLogic(preflightLogic).toDispatchActions(['loadPreflightSuccess'])+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('loads the active campaign for the current organization on mount', async () => {+ const retrieve = jest.spyOn(growthApi, 'productPushCampaignActiveRetrieve').mockResolvedValue(MOCK_CAMPAIGN)++ logic = navPanelProductPushLogic()+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['loadActiveCampaign', 'loadActiveCampaignSuccess'])+ .toMatchValues({ activeCampaign: MOCK_CAMPAIGN })+ // The current team id rides along so the backend can hide the campaign per project+ expect(retrieve).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ team_id: expect.any(Number) })+ )+ })++ it.each([+ ['a 204 no-content response', () => Promise.resolve(undefined)],+ ['a request failure', () => Promise.reject(new Error('boom'))],+ ])('exposes null (without throwing) for %s', async (_name, response) => {+ jest.spyOn(growthApi, 'productPushCampaignActiveRetrieve').mockImplementation(response as any)++ logic = navPanelProductPushLogic()+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['loadActiveCampaignSuccess'])+ .toMatchValues({ activeCampaign: null })+ })+})diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushLogic.ts b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushLogic.tsnew file mode 100644index 000000000000..85731bf46e3e--- /dev/null+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushLogic.ts@@ -0,0 +1,63 @@+import { afterMount, connect, kea, listeners, path } from 'kea'+import { loaders } from 'kea-loaders'++import { organizationLogic } from 'scenes/organizationLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { teamLogic } from 'scenes/teamLogic'++import * as api from 'products/growth/frontend/generated/api'+import type { ProductPushCampaignApi } from 'products/growth/frontend/generated/api.schemas'++import type { navPanelProductPushLogicType } from './navPanelProductPushLogicType'++export const navPanelProductPushLogic = kea<navPanelProductPushLogicType>([+ path(['lib', 'components', 'NavPanelAdvertisement', 'navPanelProductPushLogic']),+ connect(() => ({+ values: [+ organizationLogic,+ ['currentOrganization'],+ preflightLogic,+ ['isCloudOrDev'],+ teamLogic,+ ['currentTeamId'],+ ],+ })),+ loaders(({ values }) => ({+ activeCampaign: [+ null as ProductPushCampaignApi | null,+ {+ loadActiveCampaign: async (): Promise<ProductPushCampaignApi | null> => {+ if (!values.isCloudOrDev || !values.currentOrganization) {+ return null+ }++ try {+ // team_id lets the backend hide the campaign in projects that already+ // use the product. 204 (nothing to show) resolves to undefined.+ return (+ (await api.productPushCampaignActiveRetrieve(+ values.currentOrganization.id,+ values.currentTeamId ? { team_id: values.currentTeamId } : undefined+ )) ?? null+ )+ } catch {+ // The promo card is best-effort — never surface an error toast for it+ return null+ }+ },+ },+ ],+ })),+ listeners(({ actions, values }) => ({+ // The afterMount load may race preflight: its loader gate returns null until+ // preflight resolves, so retry once cloud-ness is actually known.+ [preflightLogic.actionTypes.loadPreflightSuccess]: () => {+ if (values.activeCampaign === null && !values.activeCampaignLoading) {+ actions.loadActiveCampaign()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadActiveCampaign()+ }),+])diff --git a/posthog/dags/locations/growth.py b/posthog/dags/locations/growth.pyindex e11c4f417747..5334d78acb21 100644--- a/posthog/dags/locations/growth.py+++ b/posthog/dags/locations/growth.py@@ -4,6 +4,7 @@ from products.growth.dags import (github_sdk_versions,identity_matching,oauth,+ product_push_campaigns,team_production_event_activation,user_product_list,)@@ -17,6 +18,7 @@ jobs = [user_product_list.sync_colleagues_products_monthly_job,user_product_list.sync_cross_sell_products_monthly_job,team_production_event_activation.detect_first_team_production_event_job,+ product_push_campaigns.product_push_campaigns_job,]# Identity matching processes internal PostHog data that only exists on Cloud US (team 2),# so the job is not registered on Cloud EU.@@ -31,6 +33,7 @@ defs = dagster.Definitions(user_product_list.sync_colleagues_products_monthly_schedule,user_product_list.sync_cross_sell_products_monthly_schedule,team_production_event_activation.detect_first_team_production_event_schedule,+ product_push_campaigns.product_push_campaigns_schedule,],loggers=loggers,resources=resources,diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.pyindex e9dbd764ddf0..734ec84548cc 100644--- a/posthog/models/product_intent/product_intent.py+++ b/posthog/models/product_intent/product_intent.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom datetime import UTC, datetimefrom typing import Any, Optional@@ -240,20 +241,8 @@ class ProductIntent(UUIDTModel, RootTeamMixin):self.activation_last_checked_at = datetime.now(tz=UTC)self.save()- activation_checks = {- "data_warehouse": self.has_activated_data_warehouse,- "experiments": self.has_activated_experiments,- "feature_flags": self.has_activated_feature_flags,- "session_replay": self.has_activated_session_replay,- "error_tracking": self.has_activated_error_tracking,- "product_analytics": self.has_activated_product_analytics,- "surveys": self.has_activated_surveys,- "llm_analytics": self.has_activated_llm_analytics,- "mcp_analytics": self.has_activated_mcp_analytics,- "workflows": self.has_activated_workflows,- }-- if self.product_type in activation_checks and activation_checks[self.product_type]():+ activation_check = ACTIVATION_CHECKS.get(self.product_type)+ if activation_check is not None and activation_check(self):self.activated_at = datetime.now(tz=UTC)self.save()if not skip_reporting:@@ -338,6 +327,25 @@ class ProductIntent(UUIDTModel, RootTeamMixin):return product_intent+# Dispatch for `check_and_update_activation`. Module-level so other systems can tell+# which product keys have a concrete activation criterion (vs. intent-existence only)+# without duplicating this list.+ACTIVATION_CHECKS: dict[str, Callable[[ProductIntent], bool]] = {+ "data_warehouse": ProductIntent.has_activated_data_warehouse,+ "experiments": ProductIntent.has_activated_experiments,+ "feature_flags": ProductIntent.has_activated_feature_flags,+ "session_replay": ProductIntent.has_activated_session_replay,+ "error_tracking": ProductIntent.has_activated_error_tracking,+ "product_analytics": ProductIntent.has_activated_product_analytics,+ "surveys": ProductIntent.has_activated_surveys,+ "llm_analytics": ProductIntent.has_activated_llm_analytics,+ "mcp_analytics": ProductIntent.has_activated_mcp_analytics,+ "workflows": ProductIntent.has_activated_workflows,+}++ACTIVATION_CHECK_PRODUCT_KEYS: frozenset[str] = frozenset(ACTIVATION_CHECKS)++@shared_task(ignore_result=True)@skip_team_scope_auditdef calculate_product_activation(team_id: int, only_calc_if_days_since_last_checked: int = 1) -> None:diff --git a/products/growth/backend/admin.py b/products/growth/backend/admin.pynew file mode 100644index 000000000000..62f48a9beff5--- /dev/null+++ b/products/growth/backend/admin.py@@ -0,0 +1,261 @@+from datetime import UTC, datetime+from typing import Any++from django import forms+from django.contrib import admin, messages+from django.core.exceptions import ValidationError+from django.http import HttpRequest+from django.urls import reverse+from django.utils.html import format_html+from django.utils.safestring import SafeString++import structlog++from posthog.admin.inline_registry import register_admin_inline+from posthog.models.organization import Organization+from posthog.schema_enums import ProductKey++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.selection import select_next_product+from products.growth.backend.product_push.service import cancel_campaigns, get_eligible_organization_queryset++logger = structlog.get_logger(__name__)++# Words that should stay upper-cased when a product key is humanized for the admin dropdown.+_PRODUCT_KEY_ACRONYMS = {"ai", "api", "cdp", "llm", "mcp", "sdk"}+++def humanize_product_key(product_key: str) -> str:+ """'llm_clusters' -> 'LLM clusters', 'product_analytics' -> 'Product analytics'."""+ words = product_key.split("_")+ parts = [w.upper() if w in _PRODUCT_KEY_ACRONYMS else w for w in words]+ if parts and parts[0].islower():+ parts[0] = parts[0].capitalize()+ return " ".join(parts)+++class ProductPushCampaignForm(forms.ModelForm):+ """TAM-facing form: product_key constrained to ProductKey at runtime (the model+ keeps a plain CharField so the enum can grow without migrations), and rows that+ already started or closed only accept reason_text edits."""++ class Meta:+ model = ProductPushCampaign+ fields = "__all__"++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ if "product_key" in self.fields:+ self.fields["product_key"] = forms.ChoiceField(+ # Display humanized names but keep the raw ProductKey as the stored value.+ choices=[+ (key.value, humanize_product_key(key.value)) for key in sorted(ProductKey, key=lambda k: k.value)+ ],+ label="Product",+ help_text="Which product to promote in the org's in-app push card.",+ )+ # The model field names read like internals; give the TAM plainer labels and hints.+ if "position" in self.fields:+ self.fields["position"].label = "Queue position"+ self.fields["position"].help_text = (+ "Order among this org's scheduled campaigns - lower runs sooner (0 is next up). "+ "Leave at 0 to let the daily job pick the order."+ )+ if "reason_text" in self.fields:+ self.fields["reason_text"].label = "Promo copy"+ if "scheduled_for" in self.fields:+ self.fields["scheduled_for"].label = "Start no earlier than"++ def clean(self) -> dict[str, Any] | None:+ cleaned_data = super().clean()+ # self.instance still holds DB values here (_post_clean runs after clean).+ if self.instance.pk and self.instance.status != ProductPushCampaign.Status.SCHEDULED:+ immutable_changes = set(self.changed_data) - {"reason_text"}+ if immutable_changes:+ raise ValidationError(+ f"Campaign is {self.instance.status}; only the reason text can still be edited "+ f"(attempted: {', '.join(sorted(immutable_changes))}). Use the cancel action to stop it."+ )+ return cleaned_data++[email protected](ProductPushCampaign)+class ProductPushCampaignAdmin(admin.ModelAdmin):+ form = ProductPushCampaignForm+ # FK to posthog.Organization — without this the add view renders a <select>+ # of every org on Cloud, which times out.+ autocomplete_fields = ("organization",)+ list_display = (+ "id",+ "organization_link",+ "product_key",+ "status",+ "position",+ "scheduled_for",+ "started_at",+ "ends_at",+ "ended_at",+ "source",+ "created_by",+ )+ list_display_links = ("id",)+ list_editable = ("position", "scheduled_for")+ list_filter = ("status", "source", "product_key")+ search_fields = ("id", "organization__name", "product_key")+ ordering = ("-created_at",)+ show_full_result_count = False+ list_select_related = ("organization", "created_by")+ actions = ("cancel_selected_campaigns",)++ fields = (+ "id",+ "organization",+ "product_key",+ "status",+ "position",+ "scheduled_for",+ "reason_text",+ "started_at",+ "ends_at",+ "ended_at",+ "source",+ "created_by",+ "created_at",+ "updated_at",+ )++ def get_readonly_fields(self, request: HttpRequest, obj: ProductPushCampaign | None = None) -> tuple[str, ...]:+ # Lifecycle fields are only ever written by the campaign service / dag.+ readonly: tuple[str, ...] = (+ "id",+ "status",+ "started_at",+ "ends_at",+ "ended_at",+ "source",+ "created_by",+ "created_at",+ "updated_at",+ )+ if obj is None:+ return readonly+ readonly = (*readonly, "organization")+ if obj.status != ProductPushCampaign.Status.SCHEDULED:+ # Belt: the form's clean() is the braces (it also covers list_editable).+ readonly = (*readonly, "product_key", "position", "scheduled_for")+ return readonly++ def get_fields(self, request: HttpRequest, obj: ProductPushCampaign | None = None) -> Any:+ if obj is None:+ return ("organization", "product_key", "position", "scheduled_for", "reason_text")+ return self.fields++ def get_changelist_form(self, request: HttpRequest, **kwargs: Any) -> Any:+ # list_editable rows must go through the same guard as the change form.+ kwargs.setdefault("form", ProductPushCampaignForm)+ return super().get_changelist_form(request, **kwargs)++ def has_delete_permission(self, request: HttpRequest, obj: ProductPushCampaign | None = None) -> bool:+ # Deleting a SCHEDULED row just removes it from the queue; started/closed+ # rows are the push history and must survive.+ if obj is not None and obj.status != ProductPushCampaign.Status.SCHEDULED:+ return False+ return super().has_delete_permission(request, obj)++ def save_model(self, request: HttpRequest, obj: ProductPushCampaign, form: Any, change: bool) -> None:+ if not change:+ obj.source = ProductPushCampaign.Source.TAM+ if request.user.is_authenticated:+ obj.created_by = request.user+ super().save_model(request, obj, form, change)++ @admin.action(description="Cancel selected campaigns (scheduled or active)")+ def cancel_selected_campaigns(self, request: HttpRequest, queryset: Any) -> None:+ cancelled = cancel_campaigns(+ [str(campaign_id) for campaign_id in queryset.values_list("id", flat=True)],+ now=datetime.now(tz=UTC),+ )+ skipped = queryset.count() - cancelled+ message = f"Cancelled {cancelled} campaign(s)."+ if skipped:+ message += f" {skipped} already-closed row(s) were left untouched."+ self.message_user(request, message, level=messages.INFO)++ @admin.display(description="Organization", ordering="organization__name")+ def organization_link(self, campaign: ProductPushCampaign) -> SafeString:+ url = reverse("admin:posthog_organization_change", args=[campaign.organization_id])+ return format_html('<a href="{}">{}</a>', url, campaign.organization.name)+++class ProductPushCampaignInlineForm(ProductPushCampaignForm):+ class Meta:+ model = ProductPushCampaign+ exclude = ("organization",)+++class ProductPushCampaignInline(admin.TabularInline):+ """An organization's push schedule and history on the Organization admin page.++ TAMs steer the queue here: add a row (defaults to scheduled, promoted by the+ daily job), reorder via position, or pin to a date via scheduled_for.+ """++ model = ProductPushCampaign+ form = ProductPushCampaignInlineForm+ extra = 1+ show_change_link = True+ can_delete = False+ template = "admin/growth/edit_inline/campaign_tabular.html"+ ordering = ("status", "position", "-created_at")++ fields = ("product_key", "status", "position", "scheduled_for", "reason_text", "started_at", "ended_at", "source")+ readonly_fields = ("status", "started_at", "ended_at", "source")++ def get_formset(self, request: HttpRequest, obj: Organization | None = None, **kwargs: Any) -> Any:+ formset_class = super().get_formset(request, obj, **kwargs)+ user = request.user++ class CampaignFormSet(formset_class): # type: ignore[valid-type,misc]+ # Rows added through the inline are saved by OrganizationAdmin's default+ # save_formset (which core owns), so TAM attribution happens here.+ def save_new(self, form: Any, commit: bool = True) -> ProductPushCampaign:+ instance: ProductPushCampaign = super().save_new(form, commit=False)+ instance.source = ProductPushCampaign.Source.TAM+ if instance.created_by_id is None and user.is_authenticated:+ instance.created_by = user+ if commit:+ instance.save()+ return instance++ CampaignFormSet.next_up_preview = _next_up_preview(obj) if obj is not None else ""+ return CampaignFormSet+++def _next_up_preview(organization: Organization) -> str:+ """One line telling the TAM what the daily job would do for this org next."""+ try:+ now = datetime.now(tz=UTC)+ active = ProductPushCampaign.objects.filter(+ organization=organization, status=ProductPushCampaign.Status.ACTIVE+ ).first()+ if active is not None:+ ends = f", ends {active.ends_at:%Y-%m-%d}" if active.ends_at else ""+ return f"Pushing now: {active.product_key}{ends}."++ selection = select_next_product(organization, now)+ if selection is None:+ return "Next auto pick: nothing — every blessed product is already used, pending, or in retry cooldown."++ origin = "TAM-scheduled" if selection.scheduled_campaign is not None else "blessed order"+ eligible_now = get_eligible_organization_queryset(now).filter(id=organization.id).exists()+ timing = "org is eligible now" if eligible_now else "waiting on signup grace / cooldown"+ return f"Next auto pick: {selection.product_key} ({origin}); {timing}."+ except Exception:+ # The preview is informational — never break the Organization page over it.+ logger.exception("product_push_next_up_preview_failed", organization_id=str(organization.id))+ return ""+++# Surface the inline on core's Organization admin page without core importing the+# product. OrganizationAdmin pulls it in via get_inlines() — see posthog.admin.inline_registry.+register_admin_inline(Organization, ProductPushCampaignInline)diff --git a/products/growth/backend/api/product_push.py b/products/growth/backend/api/product_push.pynew file mode 100644index 000000000000..c7684747b313--- /dev/null+++ b/products/growth/backend/api/product_push.py@@ -0,0 +1,114 @@+from typing import cast++from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import NotFound, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.products import Products+from posthog.rbac.user_access_control import UserAccessControl+from posthog.schema_enums import ProductKey++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.selection import PUSH_PRODUCT_PATHS, project_uses_product+++class ProductPushCampaignSerializer(serializers.ModelSerializer):+ id = serializers.UUIDField(+ read_only=True,+ help_text="Campaign id. Stable for the campaign's lifetime — key per-user dismissal state on it.",+ )+ product_key = serializers.CharField(+ read_only=True,+ help_text="ProductKey value of the product being pushed (e.g. 'session_replay').",+ )+ product_path = serializers.SerializerMethodField(+ help_text="Sidebar path of the pushed product in the product catalog, for display resolution. "+ "Null when the key maps to no released catalog item.",+ )+ reason_text = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Custom promo copy written by the TAM. Null means the client should use its default copy.",+ )+ started_at = serializers.DateTimeField(read_only=True, help_text="When this campaign started.")+ ends_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When this campaign is planned to end."+ )++ class Meta:+ model = ProductPushCampaign+ fields = ["id", "product_key", "product_path", "reason_text", "started_at", "ends_at"]+ read_only_fields = fields++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_product_path(self, campaign: ProductPushCampaign) -> str | None:+ try:+ product_key = ProductKey(campaign.product_key)+ except ValueError:+ return None+ # Curated mapping first — intent→product inference is ambiguous for+ # several keys (see PUSH_PRODUCT_PATHS). The inference fallback covers+ # TAM-scheduled keys outside the push lists.+ curated_path = PUSH_PRODUCT_PATHS.get(product_key)+ if curated_path is not None:+ return curated_path+ products = Products.get_products_by_intent(product_key)+ return products[0].path if products else None+++class ProductPushCampaignViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """Read-only view of an organization's product push campaign state.++ The organization_id parent lookup scopes the queryset; org membership is+ enforced by the mixin's default permissions.+ """++ scope_object = "INTERNAL"+ serializer_class = ProductPushCampaignSerializer+ queryset = ProductPushCampaign.objects.all()++ @extend_schema(+ description="The organization's currently active product push campaign. 204 when no campaign is "+ "active, or when the given project already uses the campaign's product.",+ parameters=[+ OpenApiParameter(+ name="team_id",+ type=int,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Team id of the project the caller is viewing. When that project already uses "+ "the campaign's product, the response is 204 so the promo isn't shown there.",+ )+ ],+ responses={200: ProductPushCampaignSerializer, 204: None, 404: None},+ )+ @action(detail=False, methods=["GET"])+ def active(self, request: Request, **kwargs) -> Response:+ campaign = self.get_queryset().filter(status=ProductPushCampaign.Status.ACTIVE).order_by("-started_at").first()+ if campaign is None:+ return Response(status=status.HTTP_204_NO_CONTENT)++ team_id_param = request.query_params.get("team_id")+ if team_id_param is not None:+ try:+ team_id = int(team_id_param)+ except ValueError:+ raise ValidationError({"team_id": "Must be an integer team id."})+ team = Team.objects.filter(id=team_id, organization=self.organization).first()+ if team is None:+ raise NotFound("Team not found.")+ # This is an org-scoped viewset, so the mixin's user_access_control has no team context.+ # Build a team-scoped one to check per-project access.+ team_access_control = UserAccessControl(user=cast(User, request.user), team=team)+ if not team_access_control.check_access_level_for_object(team, "member"):+ raise NotFound("Team not found.")+ if project_uses_product(team.project_id, campaign.product_key):+ return Response(status=status.HTTP_204_NO_CONTENT)++ return Response(self.get_serializer(campaign).data)diff --git a/products/growth/backend/api/test_product_push.py b/products/growth/backend/api/test_product_push.pynew file mode 100644index 000000000000..7509b5b1cb23--- /dev/null+++ b/products/growth/backend/api/test_product_push.py@@ -0,0 +1,132 @@+from datetime import timedelta+from typing import TYPE_CHECKING++from freezegun import freeze_time+from posthog.test.base import APIBaseTest++from django.utils import timezone++from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.product_intent.product_intent import ProductIntent+from posthog.models.project import Project++from products.growth.backend.models import ProductPushCampaign++if TYPE_CHECKING:+ from ee.models.rbac.access_control import AccessControl+else:+ try:+ from ee.models.rbac.access_control import AccessControl+ except ImportError:+ AccessControl = None+++class TestProductPushCampaignAPI(APIBaseTest):+ def _url(self, organization_id: str | None = None) -> str:+ return f"/api/organizations/{organization_id or self.organization.id}/product_push_campaign/active/"++ def test_active_returns_204_when_no_campaign_is_running(self) -> None:+ ProductPushCampaign.objects.create(+ organization=self.organization, product_key="surveys", status=ProductPushCampaign.Status.SCHEDULED+ )++ response = self.client.get(self._url())++ assert response.status_code == status.HTTP_204_NO_CONTENT++ @freeze_time("2026-07-03T12:00:00Z")+ def test_active_returns_the_running_campaign_with_resolved_product_path(self) -> None:+ started_at = timezone.now() - timedelta(days=3)+ campaign = ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="session_replay",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=started_at,+ ends_at=started_at + timedelta(days=30),+ reason_text="Watch real sessions.",+ )++ response = self.client.get(self._url())++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["id"] == str(campaign.id)+ assert data["product_key"] == "session_replay"+ assert data["reason_text"] == "Watch real sessions."+ assert data["product_path"]++ @freeze_time("2026-07-03T12:00:00Z")+ def test_campaign_is_hidden_in_projects_that_already_use_the_product(self) -> None:+ started_at = timezone.now() - timedelta(days=3)+ ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="session_replay",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=started_at,+ ends_at=started_at + timedelta(days=30),+ )+ _, other_team = Project.objects.create_with_team(+ initiating_user=None, organization=self.organization, name="other project"+ )+ # The current project already uses session replay; the other project doesn't.+ ProductIntent.objects.create(team=self.team, product_type="session_replay", activated_at=timezone.now())++ assert self.client.get(self._url() + f"?team_id={self.team.id}").status_code == status.HTTP_204_NO_CONTENT+ assert self.client.get(self._url() + f"?team_id={other_team.id}").status_code == status.HTTP_200_OK+ assert self.client.get(self._url() + "?team_id=99999999").status_code == status.HTTP_404_NOT_FOUND+ assert self.client.get(self._url() + "?team_id=nope").status_code == status.HTTP_400_BAD_REQUEST++ @freeze_time("2026-07-03T12:00:00Z")+ def test_restricted_team_returns_404_same_as_nonexistent(self) -> None:+ """Inaccessible teams should be indistinguishable from nonexistent ones."""+ if AccessControl is None:+ self.skipTest("EE not available")++ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()++ started_at = timezone.now() - timedelta(days=3)+ ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="session_replay",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=started_at,+ ends_at=started_at + timedelta(days=30),+ )+ _, restricted_team = Project.objects.create_with_team(+ initiating_user=None, organization=self.organization, name="restricted project"+ )+ # Make the team private (inaccessible to regular members)+ AccessControl.objects.create(+ team=restricted_team, resource="project", resource_id=str(restricted_team.id), access_level="none"+ )+ # Demote the user to member so RBAC applies+ OrganizationMembership.objects.filter(organization=self.organization, user=self.user).update(+ level=OrganizationMembership.Level.MEMBER+ )++ response = self.client.get(self._url() + f"?team_id={restricted_team.id}")++ assert response.status_code == status.HTTP_404_NOT_FOUND, (+ "Restricted teams should return 404, same as nonexistent teams"+ )++ @freeze_time("2026-07-03T12:00:00Z")+ def test_non_member_cannot_read_another_orgs_campaign(self) -> None:+ other_organization = Organization.objects.create(name="other")+ ProductPushCampaign.objects.create(+ organization=other_organization,+ product_key="session_replay",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=timezone.now(),+ )++ response = self.client.get(self._url(str(other_organization.id)))++ assert response.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)+ assert "product_key" not in (response.json() or {})diff --git a/products/growth/backend/migrations/0001_initial_migration.py b/products/growth/backend/migrations/0001_initial_migration.pynew file mode 100644index 000000000000..2e4f69c57860--- /dev/null+++ b/products/growth/backend/migrations/0001_initial_migration.py@@ -0,0 +1,122 @@+# Generated by Django 5.2.14 on 2026-07-01 23:43++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1247_oauthaccesstoken_token_idx"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="ProductPushCampaign",+ fields=[+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("product_key", models.CharField(max_length=255)),+ (+ "status",+ models.CharField(+ choices=[+ ("scheduled", "Scheduled"),+ ("active", "Active"),+ ("adopted", "Adopted"),+ ("skipped", "Skipped"),+ ("cancelled", "Cancelled"),+ ],+ default="scheduled",+ max_length=16,+ ),+ ),+ ("position", models.PositiveIntegerField(default=0)),+ (+ "scheduled_for",+ models.DateField(+ blank=True,+ help_text="Don't start before this date. Overrides the signup grace period and the between-campaigns cooldown (an explicit human decision), but never the one-active-campaign-per-org invariant. Empty = next available slot.",+ null=True,+ ),+ ),+ ("started_at", models.DateTimeField(blank=True, null=True)),+ ("ends_at", models.DateTimeField(blank=True, null=True)),+ ("ended_at", models.DateTimeField(blank=True, null=True)),+ (+ "source",+ models.CharField(+ choices=[("auto", "Auto"), ("tam", "TAM")],+ default="auto",+ max_length=8,+ ),+ ),+ (+ "reason_text",+ models.TextField(+ blank=True,+ help_text="Custom copy for the in-app promo card. Empty = default copy.",+ null=True,+ ),+ ),+ ("metadata", models.JSONField(blank=True, default=dict)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="product_push_campaigns",+ to="posthog.organization",+ ),+ ),+ ],+ options={+ "verbose_name": "Product push campaign",+ "verbose_name_plural": "Product push campaigns",+ "indexes": [+ models.Index(fields=["organization", "status"], name="growth_push_org_status"),+ models.Index(fields=["status", "ends_at"], name="growth_push_status_ends_at"),+ models.Index(+ fields=["status", "scheduled_for"],+ name="growth_push_status_sched",+ ),+ ],+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("status", "active")),+ fields=("organization",),+ name="uniq_active_product_push_per_org",+ ),+ models.UniqueConstraint(+ condition=models.Q(("status__in", ["scheduled", "active"])),+ fields=("organization", "product_key"),+ name="uniq_pending_product_push_per_org_product",+ ),+ ],+ },+ ),+ ]diff --git a/products/growth/backend/migrations/__init__.py b/products/growth/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/growth/backend/migrations/max_migration.txt b/products/growth/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..b0345048105e--- /dev/null+++ b/products/growth/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initial_migrationdiff --git a/products/growth/backend/models.py b/products/growth/backend/models.pynew file mode 100644index 000000000000..e2397d528f7e--- /dev/null+++ b/products/growth/backend/models.py@@ -0,0 +1,103 @@+from django.db import models+from django.db.models import Q++from posthog.models.utils import UpdatedMetaFields, UUIDModel+++class ProductPushCampaign(UUIDModel, UpdatedMetaFields):+ """One product pushed to a whole organization for a bounded window.++ A single table holds the queue (SCHEDULED), the current push (ACTIVE), and the+ history (ADOPTED / SKIPPED / CANCELLED) — promoting a scheduled row to active is+ a status flip, not a row move. Cadence, selection, and transitions live in+ products/growth/backend/product_push/.+ """++ class Status(models.TextChoices):+ SCHEDULED = "scheduled", "Scheduled"+ ACTIVE = "active", "Active"+ ADOPTED = "adopted", "Adopted"+ SKIPPED = "skipped", "Skipped"+ CANCELLED = "cancelled", "Cancelled"++ class Source(models.TextChoices):+ AUTO = "auto", "Auto"+ TAM = "tam", "TAM"++ # No DB constraints on the FKs: posthog_organization and posthog_user are hot+ # tables, and building an FK constraint takes a lock on the referenced parent+ # (see safe-django-migrations.md "Foreign keys to hot tables").+ organization = models.ForeignKey(+ "posthog.Organization",+ on_delete=models.CASCADE,+ related_name="product_push_campaigns",+ db_constraint=False,+ )+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ )++ # A ProductKey value. Plain CharField (like ProductIntent.product_type) so the+ # enum can grow without a migration; the admin form constrains input at runtime.+ product_key = models.CharField(max_length=255)++ status = models.CharField(max_length=16, choices=Status.choices, default=Status.SCHEDULED)++ # Ordering among an org's SCHEDULED rows; lower starts sooner.+ position = models.PositiveIntegerField(default=0)++ scheduled_for = models.DateField(+ null=True,+ blank=True,+ help_text="Don't start before this date. Overrides the signup grace period and the between-campaigns "+ "cooldown (an explicit human decision), but never the one-active-campaign-per-org invariant. "+ "Empty = next available slot.",+ )++ started_at = models.DateTimeField(null=True, blank=True)+ # Planned end (started_at + CAMPAIGN_DURATION_DAYS), denormalized so the daily+ # sweep can find expired campaigns with an index scan.+ ends_at = models.DateTimeField(null=True, blank=True)+ # Actual close time (adoption detected, expired, or cancelled).+ ended_at = models.DateTimeField(null=True, blank=True)++ source = models.CharField(max_length=8, choices=Source.choices, default=Source.AUTO)++ reason_text = models.TextField(+ null=True,+ blank=True,+ help_text="Custom copy for the in-app promo card. Empty = default copy.",+ )++ # Outcome details, e.g. {"adoption_signal": "intent_activated", "team_id": 123}.+ metadata = models.JSONField(default=dict, blank=True)++ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ verbose_name = "Product push campaign"+ verbose_name_plural = "Product push campaigns"+ constraints = [+ models.UniqueConstraint(+ fields=["organization"],+ condition=Q(status="active"),+ name="uniq_active_product_push_per_org",+ ),+ models.UniqueConstraint(+ fields=["organization", "product_key"],+ condition=Q(status__in=["scheduled", "active"]),+ name="uniq_pending_product_push_per_org_product",+ ),+ ]+ indexes = [+ models.Index(fields=["organization", "status"], name="growth_push_org_status"),+ models.Index(fields=["status", "ends_at"], name="growth_push_status_ends_at"),+ models.Index(fields=["status", "scheduled_for"], name="growth_push_status_sched"),+ ]++ def __str__(self) -> str:+ return f"{self.organization_id} - {self.product_key} ({self.status})"diff --git a/products/growth/backend/product_push/cadence.py b/products/growth/backend/product_push/cadence.pynew file mode 100644index 000000000000..9403e1c83c77--- /dev/null+++ b/products/growth/backend/product_push/cadence.py@@ -0,0 +1,48 @@+"""Cadence rules for organization product push campaigns.++Pure date math — no DB access — so the rules are unit-testable in isolation.+Campaigns are rolling windows anchored on their own start (not on the org's+signup anniversary): the between-campaigns cooldown and early adoption closes+make anniversary anchoring impossible to keep.+"""++from datetime import date, datetime, timedelta++# No pushes for this long after the organization signs up.+GRACE_PERIOD_DAYS = 10++# How long a campaign keeps pushing before it is closed as skipped.+CAMPAIGN_DURATION_DAYS = 14++# Quiet period between one campaign ending (for any reason) and the next starting.+COOLDOWN_DAYS = 7++# A skipped (or cancelled) product becomes eligible to push again after this long.+# Deliberately short enough that blessed products keep cycling — an org that skips+# everything retries the blessed order rather than draining the fallback pool.+SKIP_RETRY_DAYS = 90+++def campaign_ends_at(started_at: datetime) -> datetime:+ return started_at + timedelta(days=CAMPAIGN_DURATION_DAYS)+++def is_grace_period_over(organization_created_at: datetime, now: datetime) -> bool:+ return now >= organization_created_at + timedelta(days=GRACE_PERIOD_DAYS)+++def is_cooldown_over(last_campaign_ended_at: datetime | None, now: datetime) -> bool:+ if last_campaign_ended_at is None:+ return True+ return now >= last_campaign_ended_at + timedelta(days=COOLDOWN_DAYS)+++def is_pin_due(scheduled_for: date | None, now: datetime) -> bool:+ """An unset pin is always due; a dated pin is due from that date onward."""+ if scheduled_for is None:+ return True+ return now.date() >= scheduled_for+++def is_retry_eligible(campaign_ended_at: datetime, now: datetime) -> bool:+ return now >= campaign_ended_at + timedelta(days=SKIP_RETRY_DAYS)diff --git a/products/growth/backend/product_push/selection.py b/products/growth/backend/product_push/selection.pynew file mode 100644index 000000000000..a456540b7e84--- /dev/null+++ b/products/growth/backend/product_push/selection.py@@ -0,0 +1,163 @@+"""Next-product selection for organization product push campaigns.++TAM-scheduled rows always take precedence, in TAM-defined order. Otherwise we+walk BLESSED_PRODUCT_ORDER and pick the first product the org is not excluded+from — there is deliberately no preference between never-pushed products and+retry-eligible ones; blessed position decides. When every blessed product is+excluded we pick at random from FALLBACK_PRODUCT_ORDER.++Usage granularity is per project: ProductIntent rows are project-scoped+(RootTeamMixin pins them to the project's root team), so an org only counts as+"using" a product when a majority of its projects do. A product adopted by a+minority of projects still gets pushed to the rest of the org — the promo card+is hidden in the projects that already use it (see the API's team_id handling).+"""++from collections import defaultdict+from dataclasses import dataclass+from datetime import datetime+from random import choice++from django.db.models import Q++from posthog.models.organization import Organization+from posthog.models.product_intent.product_intent import ACTIVATION_CHECK_PRODUCT_KEYS, ProductIntent+from posthog.models.project import Project+from posthog.schema_enums import ProductKey++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.cadence import is_retry_eligible++# The order in which we push products to organizations that don't use them yet.+# Seeded from the cross-sell BASE_PREFERENCE_WEIGHTS ranking (see+# cross_sell_candidate_selector.py); extend as growth adds products to the program.+BLESSED_PRODUCT_ORDER: list[ProductKey] = [+ ProductKey.PRODUCT_ANALYTICS,+ ProductKey.WEB_ANALYTICS,+ ProductKey.SESSION_REPLAY,+ ProductKey.ERROR_TRACKING,+ ProductKey.FEATURE_FLAGS,+ ProductKey.EXPERIMENTS,+]++# Unordered pool for orgs that exhausted the blessed order; picked at random.+# Only broadly-available products belong here — nothing feature-flag-gated or+# unreleased in the catalog, since the promo card would link to a product most+# users can't open. Gated products can still be pushed to a specific org via a+# TAM-scheduled row once the flag is enabled for them.+FALLBACK_PRODUCT_ORDER: list[ProductKey] = [+ ProductKey.CONVERSATIONS,+ ProductKey.DATA_WAREHOUSE,+ ProductKey.LLM_ANALYTICS,+ ProductKey.LLM_CLUSTERS,+ ProductKey.LLM_EVALUATIONS,+ ProductKey.LLM_PROMPTS,+ ProductKey.LOGS,+ ProductKey.WORKFLOWS,+]++# Display resolution for pushable products: ProductKey → catalog path (the id the+# frontend resolves to a name, icon, and href). Explicit because intent→product+# inference is ambiguous — several keys map to multiple catalog items and the+# first match is often wrong (e.g. product_analytics's first intent match is+# 'Dashboards'). Validated against products.json in tests.+PUSH_PRODUCT_PATHS: dict[ProductKey, str] = {+ ProductKey.PRODUCT_ANALYTICS: "Product analytics",+ ProductKey.WEB_ANALYTICS: "Web analytics",+ ProductKey.SESSION_REPLAY: "Session replay",+ ProductKey.ERROR_TRACKING: "Error tracking",+ ProductKey.FEATURE_FLAGS: "Feature flags",+ ProductKey.EXPERIMENTS: "Experiments",+ ProductKey.CONVERSATIONS: "Support",+ # The 'Data warehouse' catalog item is unreleased; SQL editor is the shipped surface.+ ProductKey.DATA_WAREHOUSE: "SQL editor",+ ProductKey.LLM_ANALYTICS: "LLM analytics",+ ProductKey.LLM_CLUSTERS: "Clusters",+ ProductKey.LLM_EVALUATIONS: "Evaluations",+ ProductKey.LLM_PROMPTS: "Prompts",+ ProductKey.LOGS: "Logs",+ ProductKey.WORKFLOWS: "Workflows",+}+++@dataclass(frozen=True)+class Selection:+ product_key: str+ # Set when the pick promotes an existing TAM-scheduled row instead of creating one.+ scheduled_campaign: ProductPushCampaign | None = None+++def get_org_used_product_keys(organization: Organization) -> set[str]:+ """Product keys used in a majority of the org's projects, per ProductIntent.++ For products with an activation criterion (ACTIVATION_CHECK_PRODUCT_KEYS),+ a project "uses" the product when it has an activated intent; for the rest+ the strongest available signal is that any intent row exists at all. A+ product used by only a minority of projects is still worth pushing to the+ rest of the org.+ """+ total_projects = Project.objects.filter(organization_id=organization.id).count()+ if total_projects == 0:+ return set()++ rows = ProductIntent.objects.filter(team__organization_id=organization.id).values_list(+ "product_type", "activated_at", "team__project_id"+ )+ projects_using: defaultdict[str, set[int]] = defaultdict(set)+ for product_type, activated_at, project_id in rows:+ if product_type not in ACTIVATION_CHECK_PRODUCT_KEYS or activated_at is not None:+ projects_using[product_type].add(project_id)++ return {product for product, projects in projects_using.items() if len(projects) * 2 > total_projects}+++def project_uses_product(project_id: int, product_key: str) -> bool:+ """The per-project version of the usage signal in get_org_used_product_keys."""+ intents = ProductIntent.objects.filter(team__project_id=project_id, product_type=product_key)+ if product_key in ACTIVATION_CHECK_PRODUCT_KEYS:+ intents = intents.filter(activated_at__isnull=False)+ return intents.exists()+++def select_next_product(organization: Organization, now: datetime) -> Selection | None:+ """Pick the product the org's next campaign should push, or None when exhausted.++ Excluded from the blessed/fallback walk: products the org already uses (in a+ majority of projects), products with an ADOPTED campaign, products currently+ ACTIVE or SCHEDULED, and products whose last push ended (skipped or+ cancelled) within SKIP_RETRY_DAYS.+ """+ due_scheduled = (+ ProductPushCampaign.objects.filter(organization=organization, status=ProductPushCampaign.Status.SCHEDULED)+ .filter(Q(scheduled_for__isnull=True) | Q(scheduled_for__lte=now.date()))+ .order_by("position", "created_at")+ .first()+ )+ if due_scheduled is not None:+ return Selection(product_key=due_scheduled.product_key, scheduled_campaign=due_scheduled)++ excluded = get_org_used_product_keys(organization)++ history = ProductPushCampaign.objects.filter(organization=organization).values_list(+ "product_key", "status", "ended_at"+ )+ for product_key, status, ended_at in history:+ if status in (+ ProductPushCampaign.Status.SCHEDULED,+ ProductPushCampaign.Status.ACTIVE,+ ProductPushCampaign.Status.ADOPTED,+ ):+ excluded.add(product_key)+ elif ended_at is not None and not is_retry_eligible(ended_at, now):+ # Skipped or cancelled recently — still in retry cooldown.+ excluded.add(product_key)++ for product_key in BLESSED_PRODUCT_ORDER:+ if product_key.value not in excluded:+ return Selection(product_key=product_key.value)++ fallback_candidates = [product_key for product_key in FALLBACK_PRODUCT_ORDER if product_key.value not in excluded]+ if fallback_candidates:+ return Selection(product_key=choice(fallback_candidates).value)++ return Nonediff --git a/products/growth/backend/product_push/service.py b/products/growth/backend/product_push/service.pynew file mode 100644index 000000000000..03314988b4ac--- /dev/null+++ b/products/growth/backend/product_push/service.py@@ -0,0 +1,353 @@+"""State transitions and adoption detection for product push campaigns.++Adoption is ProductIntent-based for v1. Extension path: plug ClickHouse usage+counters (posthog/tasks/usage_report.py `get_teams_with_*_count_in_period`+helpers) as a second source inside `org_adopted_product` — its contract stays+fixed. We deliberately never create intents ourselves; that would corrupt the+intent metric.+"""++from dataclasses import dataclass+from datetime import UTC, datetime, timedelta++from django.db import IntegrityError, transaction+from django.db.models import Exists, OuterRef, Q, QuerySet++import structlog++from posthog.event_usage import groups+from posthog.exceptions_capture import capture_exception+from posthog.models.organization import Organization+from posthog.models.product_intent.product_intent import ACTIVATION_CHECK_PRODUCT_KEYS, ProductIntent+from posthog.ph_client import ph_scoped_capture++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.cadence import (+ COOLDOWN_DAYS,+ GRACE_PERIOD_DAYS,+ campaign_ends_at,+ is_cooldown_over,+ is_grace_period_over,+)+from products.growth.backend.product_push.selection import Selection, select_next_product++logger = structlog.get_logger(__name__)++# Re-check a not-yet-activated intent's criterion at most this often. Matches the+# cadence of `calculate_product_activation`'s debounce.+ACTIVATION_RECHECK_STALENESS = timedelta(days=1)+++@dataclass(frozen=True)+class AdoptionResult:+ signal: str # "intent_activated" | "intent_created"+ team_id: int+++@dataclass(kw_only=True)+class CloseBatchResult:+ evaluated: int = 0+ adopted: int = 0+ skipped: int = 0+++@dataclass(kw_only=True)+class StartBatchResult:+ orgs_processed: int = 0+ started: int = 0+ no_candidate: int = 0+ not_eligible: int = 0+ conflicts: int = 0+ would_start: int = 0 # dry-run only+++def org_adopted_product(organization_id: str, product_key: str, since: datetime) -> AdoptionResult | None:+ """Did any team in the org start using the product after `since`?"""+ intents = ProductIntent.objects.filter(team__organization_id=organization_id, product_type=product_key)++ if product_key not in ACTIVATION_CHECK_PRODUCT_KEYS:+ # No activation criterion exists — the strongest signal we have is that+ # someone showed intent during the campaign.+ created = intents.filter(created_at__gte=since).order_by("created_at").first()+ if created is not None:+ return AdoptionResult(signal="intent_created", team_id=created.team_id)+ return None++ # Proactively re-check stale intents: the Celery re-check path only fires when+ # someone re-registers intent, so without this a team that quietly meets the+ # criterion mid-campaign would never flip activated_at.+ stale_cutoff = datetime.now(UTC) - ACTIVATION_RECHECK_STALENESS+ stale_intents = intents.filter(activated_at__isnull=True).filter(+ Q(activation_last_checked_at__isnull=True) | Q(activation_last_checked_at__lt=stale_cutoff)+ )+ for intent in stale_intents:+ try:+ intent.check_and_update_activation()+ except Exception as e:+ capture_exception(e, {"team": "team-growth", "organization_id": organization_id})+ logger.exception("product_push_activation_recheck_failed", intent_id=intent.id)++ activated = intents.filter(activated_at__gte=since).order_by("activated_at").first()+ if activated is not None:+ return AdoptionResult(signal="intent_activated", team_id=activated.team_id)+ return None+++def get_eligible_organization_queryset(now: datetime) -> QuerySet[Organization]:+ """Organizations that may start a campaign right now.++ Past the signup grace period, no active campaign, out of the between-campaigns+ cooldown — or holding a due dated TAM pin, which overrides grace and cooldown.+ """+ grace_cutoff = now - timedelta(days=GRACE_PERIOD_DAYS)+ cooldown_cutoff = now - timedelta(days=COOLDOWN_DAYS)++ active = ProductPushCampaign.objects.filter(+ organization_id=OuterRef("id"), status=ProductPushCampaign.Status.ACTIVE+ )+ recently_ended = ProductPushCampaign.objects.filter(organization_id=OuterRef("id"), ended_at__gt=cooldown_cutoff)+ due_pin = ProductPushCampaign.objects.filter(+ organization_id=OuterRef("id"),+ status=ProductPushCampaign.Status.SCHEDULED,+ scheduled_for__isnull=False,+ scheduled_for__lte=now.date(),+ )++ return (+ Organization.objects.exclude(for_internal_metrics=True)+ .annotate(has_active=Exists(active), has_recent_end=Exists(recently_ended), has_due_pin=Exists(due_pin))+ .filter(has_active=False)+ .filter(Q(created_at__lte=grace_cutoff, has_recent_end=False) | Q(has_due_pin=True))+ )+++def evaluate_and_close_campaign_batch(campaign_ids: list[str], now: datetime) -> CloseBatchResult:+ """Close active campaigns: adopted when the org started using the product,+ skipped when the window expired without adoption.++ Concurrent-safe: the status flip runs under SELECT FOR UPDATE SKIP LOCKED, so a+ parallel run closes each campaign (and emits its event) at most once.+ """+ result = CloseBatchResult()+ closed: list[tuple[ProductPushCampaign, str]] = []++ campaigns = ProductPushCampaign.objects.filter(+ id__in=campaign_ids, status=ProductPushCampaign.Status.ACTIVE+ ).select_related("organization")++ for campaign in campaigns:+ if campaign.started_at is None:+ continue+ result.evaluated += 1++ # The adoption check reads (and may re-check/save) intents — keep it outside+ # the row lock below.+ adoption = org_adopted_product(str(campaign.organization_id), campaign.product_key, since=campaign.started_at)++ if adoption is not None:+ new_status = ProductPushCampaign.Status.ADOPTED+ elif campaign.ends_at is not None and now >= campaign.ends_at:+ new_status = ProductPushCampaign.Status.SKIPPED+ else:+ continue++ with transaction.atomic():+ locked = (+ ProductPushCampaign.objects.select_for_update(skip_locked=True)+ .filter(id=campaign.id, status=ProductPushCampaign.Status.ACTIVE)+ .first()+ )+ if locked is None:+ continue+ locked.status = new_status+ locked.ended_at = now+ if adoption is not None:+ locked.metadata = {+ **(locked.metadata or {}),+ "adoption_signal": adoption.signal,+ "adoption_team_id": adoption.team_id,+ }+ locked.save(update_fields=["status", "ended_at", "metadata", "updated_at"])++ campaign.refresh_from_db(fields=["status", "ended_at", "metadata"])+ if new_status == ProductPushCampaign.Status.ADOPTED:+ result.adopted += 1+ closed.append((campaign, "adopted"))+ else:+ result.skipped += 1+ closed.append((campaign, "skipped"))+ logger.info(+ "product_push_campaign_closed",+ campaign_id=str(campaign.id),+ organization_id=str(campaign.organization_id),+ product_key=campaign.product_key,+ status=new_status,+ )++ _capture_campaign_events(closed)+ return result+++def start_campaigns_for_org_batch(+ organization_ids: list[str], now: datetime, dry_run: bool = False+) -> StartBatchResult:+ """Start the next campaign for each eligible org in the batch.++ Eligibility is re-checked per org (the caller's eligible-set may be stale), and+ the one-active-per-org partial unique constraint makes concurrent starts+ idempotent. A due dated TAM pin bypasses grace and cooldown.+ """+ result = StartBatchResult()+ started: list[tuple[ProductPushCampaign, str]] = []++ organizations = Organization.objects.filter(id__in=organization_ids).only("id", "created_at", "customer_id")++ for organization in organizations:+ result.orgs_processed += 1++ selection = select_next_product(organization, now)+ if selection is None:+ result.no_candidate += 1+ continue++ if not _is_eligible_for_selection(organization, selection, now):+ result.not_eligible += 1+ continue++ if dry_run:+ result.would_start += 1+ logger.info(+ "product_push_campaign_would_start",+ organization_id=str(organization.id),+ product_key=selection.product_key,+ promotes_scheduled_row=selection.scheduled_campaign is not None,+ )+ continue++ campaign = _start_campaign(organization, selection, now)+ if campaign is None:+ result.conflicts += 1+ continue++ result.started += 1+ started.append((campaign, "started"))+ logger.info(+ "product_push_campaign_started",+ campaign_id=str(campaign.id),+ organization_id=str(organization.id),+ product_key=campaign.product_key,+ source=campaign.source,+ )++ _capture_campaign_events(started)+ return result+++def cancel_campaigns(campaign_ids: list[str], now: datetime) -> int:+ """Cancel SCHEDULED or ACTIVE campaigns (admin action). Returns the count cancelled."""+ cancelled: list[tuple[ProductPushCampaign, str]] = []+ with transaction.atomic():+ campaigns = list(+ ProductPushCampaign.objects.select_for_update(skip_locked=True)+ .filter(+ id__in=campaign_ids,+ status__in=[ProductPushCampaign.Status.SCHEDULED, ProductPushCampaign.Status.ACTIVE],+ )+ .select_related("organization")+ )+ for campaign in campaigns:+ campaign.status = ProductPushCampaign.Status.CANCELLED+ campaign.ended_at = now+ campaign.save(update_fields=["status", "ended_at", "updated_at"])+ cancelled.append((campaign, "cancelled"))++ _capture_campaign_events(cancelled)+ return len(cancelled)+++def _is_eligible_for_selection(organization: Organization, selection: Selection, now: datetime) -> bool:+ # One active campaign per org — nothing overrides this, not even a dated pin.+ if ProductPushCampaign.objects.filter(organization=organization, status=ProductPushCampaign.Status.ACTIVE).exists():+ return False++ # A due dated pin is an explicit TAM decision — it bypasses grace and cooldown.+ is_dated_pin = selection.scheduled_campaign is not None and selection.scheduled_campaign.scheduled_for is not None+ if is_dated_pin:+ return True++ if not is_grace_period_over(organization.created_at, now):+ return False++ last_ended_at = (+ ProductPushCampaign.objects.filter(organization=organization, ended_at__isnull=False)+ .order_by("-ended_at")+ .values_list("ended_at", flat=True)+ .first()+ )+ return is_cooldown_over(last_ended_at, now)+++def _start_campaign(organization: Organization, selection: Selection, now: datetime) -> ProductPushCampaign | None:+ ends_at = campaign_ends_at(now)+ try:+ with transaction.atomic():+ if selection.scheduled_campaign is not None:+ campaign = (+ ProductPushCampaign.objects.select_for_update(skip_locked=True)+ .filter(id=selection.scheduled_campaign.id, status=ProductPushCampaign.Status.SCHEDULED)+ .first()+ )+ if campaign is None:+ return None+ campaign.status = ProductPushCampaign.Status.ACTIVE+ campaign.started_at = now+ campaign.ends_at = ends_at+ campaign.save(update_fields=["status", "started_at", "ends_at", "updated_at"])+ return campaign+ return ProductPushCampaign.objects.create(+ organization=organization,+ product_key=selection.product_key,+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=now,+ ends_at=ends_at,+ source=ProductPushCampaign.Source.AUTO,+ )+ except IntegrityError:+ # Another worker started a campaign for this org concurrently — the partial+ # unique constraint makes this a no-op rather than a duplicate push.+ return None+++def _capture_campaign_events(campaign_events: list[tuple[ProductPushCampaign, str]]) -> None:+ """Emit one analytics event per transition, after the transactions committed.++ At-most-once: rows are already transitioned, so a crash before flush loses those+ events; the table is the source of truth. Per-row guard keeps one bad org from+ forfeiting the rest of the batch.+ """+ if not campaign_events:+ return++ with ph_scoped_capture() as capture:+ for campaign, transition in campaign_events:+ try:+ properties = {+ "campaign_id": str(campaign.id),+ "product_key": campaign.product_key,+ "source": campaign.source,+ "adoption_signal": (campaign.metadata or {}).get("adoption_signal"),+ "days_active": (+ (campaign.ended_at - campaign.started_at).days+ if campaign.ended_at and campaign.started_at+ else None+ ),+ }+ capture(+ distinct_id=str(campaign.organization_id),+ event=f"product push campaign {transition}",+ properties={key: value for key, value in properties.items() if value is not None},+ groups=groups(organization=campaign.organization),+ )+ except Exception as e:+ capture_exception(e, {"team": "team-growth", "campaign_id": str(campaign.id)})+ logger.exception("product_push_campaign_capture_failed", campaign_id=str(campaign.id))diff --git a/products/growth/backend/routes.py b/products/growth/backend/routes.pyindex 3eddb1e05ab1..ee8124408357 100644--- a/products/growth/backend/routes.py+++ b/products/growth/backend/routes.py@@ -1,9 +1,16 @@from posthog.api.routing import RouterRegistryfrom products.growth.backend.api.identity_matching import IdentityMatchingLinkViewSet+from products.growth.backend.api.product_push import ProductPushCampaignViewSetdef register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"identity_matching_links", IdentityMatchingLinkViewSet, "project_identity_matching_links", ["team_id"])+ routers.organizations.register(+ r"product_push_campaign",+ ProductPushCampaignViewSet,+ "organization_product_push_campaign",+ ["organization_id"],+ )diff --git a/products/growth/backend/templates/admin/growth/edit_inline/campaign_tabular.html b/products/growth/backend/templates/admin/growth/edit_inline/campaign_tabular.htmlnew file mode 100644index 000000000000..e323ced50345--- /dev/null+++ b/products/growth/backend/templates/admin/growth/edit_inline/campaign_tabular.html@@ -0,0 +1,7 @@+{% include "admin/edit_inline/tabular.html" %}++{% if inline_admin_formset.formset.next_up_preview %}+<p style="margin: 8px 0 24px;">+ {{ inline_admin_formset.formset.next_up_preview }}+</p>+{% endif %}diff --git a/products/growth/backend/tests/test_product_push_admin.py b/products/growth/backend/tests/test_product_push_admin.pynew file mode 100644index 000000000000..0a3dd2b926b2--- /dev/null+++ b/products/growth/backend/tests/test_product_push_admin.py@@ -0,0 +1,103 @@+from typing import Any++from posthog.test.base import BaseTest++from django.contrib.admin import AdminSite+from django.test import RequestFactory+from django.urls import reverse++from posthog.models.organization import Organization++from products.growth.backend.admin import ProductPushCampaignAdmin, ProductPushCampaignInline+from products.growth.backend.models import ProductPushCampaign+++class TestProductPushCampaignAdmin(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ self.admin = ProductPushCampaignAdmin(ProductPushCampaign, AdminSite())+ self.request_factory = RequestFactory()++ def _request(self) -> Any:+ request = self.request_factory.get("/admin/growth/productpushcampaign/")+ request.user = self.user+ return request++ def test_organization_page_renders_schedule_inline_with_next_up_preview(self) -> None:+ ProductPushCampaign.objects.create(+ organization=self.organization, product_key="surveys", status=ProductPushCampaign.Status.SCHEDULED+ )+ self.client.force_login(self.user)++ response = self.client.get(reverse("admin:posthog_organization_change", args=[self.organization.pk]))++ assert response.status_code == 200+ assert "Next auto pick: surveys" in response.content.decode()++ def test_campaign_changelist_renders(self) -> None:+ ProductPushCampaign.objects.create(+ organization=self.organization, product_key="surveys", status=ProductPushCampaign.Status.ACTIVE+ )+ self.client.force_login(self.user)++ response = self.client.get(reverse("admin:growth_productpushcampaign_changelist"))++ assert response.status_code == 200++ def test_changelist_edits_are_rejected_once_a_campaign_left_the_queue(self) -> None:+ skipped = ProductPushCampaign.objects.create(+ organization=self.organization, product_key="surveys", status=ProductPushCampaign.Status.SKIPPED+ )+ scheduled = ProductPushCampaign.objects.create(+ organization=self.organization, product_key="error_tracking", status=ProductPushCampaign.Status.SCHEDULED+ )+ # The changelist edits rows through the formset's field-limited form.+ form_class = self.admin.get_changelist_formset(self._request()).form++ skipped_form = form_class(instance=skipped, data={"position": "5", "scheduled_for": ""})+ assert not skipped_form.is_valid()+ assert "cancel action" in str(skipped_form.errors)++ scheduled_form = form_class(instance=scheduled, data={"position": "5", "scheduled_for": ""})+ assert scheduled_form.is_valid(), scheduled_form.errors++ def test_reason_text_stays_editable_on_a_started_campaign(self) -> None:+ active = ProductPushCampaign.objects.create(+ organization=self.organization, product_key="surveys", status=ProductPushCampaign.Status.ACTIVE+ )+ request = self._request()+ form_class = self.admin.get_form(request, obj=active, change=True)++ form = form_class(instance=active, data={"reason_text": "Fresh copy for the promo card"})++ assert form.is_valid(), form.errors++ def test_inline_rows_are_attributed_to_the_tam_who_added_them(self) -> None:+ inline = ProductPushCampaignInline(Organization, AdminSite())+ request = self.request_factory.post("/admin/posthog/organization/")+ request.user = self.user+ formset_class = inline.get_formset(request, self.organization)+ prefix = formset_class.get_default_prefix()++ formset = formset_class(+ instance=self.organization,+ data={+ f"{prefix}-TOTAL_FORMS": "1",+ f"{prefix}-INITIAL_FORMS": "0",+ f"{prefix}-MIN_NUM_FORMS": "0",+ f"{prefix}-MAX_NUM_FORMS": "1000",+ f"{prefix}-0-id": "",+ f"{prefix}-0-product_key": "surveys",+ f"{prefix}-0-position": "0",+ f"{prefix}-0-scheduled_for": "",+ f"{prefix}-0-reason_text": "",+ },+ )++ assert formset.is_valid(), formset.errors+ (campaign,) = formset.save()+ assert campaign.status == ProductPushCampaign.Status.SCHEDULED+ assert campaign.source == ProductPushCampaign.Source.TAM+ assert campaign.created_by == self.userdiff --git a/products/growth/backend/tests/test_product_push_cadence.py b/products/growth/backend/tests/test_product_push_cadence.pynew file mode 100644index 000000000000..4e596dd0b37a--- /dev/null+++ b/products/growth/backend/tests/test_product_push_cadence.py@@ -0,0 +1,59 @@+from datetime import UTC, date, datetime++from django.test import SimpleTestCase++from parameterized import parameterized++from products.growth.backend.product_push.cadence import (+ campaign_ends_at,+ is_cooldown_over,+ is_grace_period_over,+ is_pin_due,+ is_retry_eligible,+)++NOW = datetime(2026, 7, 1, 12, 0, tzinfo=UTC)+++class TestProductPushCadence(SimpleTestCase):+ @parameterized.expand(+ [+ ("day_9_still_in_grace", datetime(2026, 6, 22, 13, 0, tzinfo=UTC), False),+ ("day_10_exactly_over", datetime(2026, 6, 21, 12, 0, tzinfo=UTC), True),+ ("day_11_over", datetime(2026, 6, 20, 12, 0, tzinfo=UTC), True),+ ]+ )+ def test_grace_period_boundary(self, _name: str, org_created_at: datetime, expected: bool) -> None:+ assert is_grace_period_over(org_created_at, NOW) is expected++ @parameterized.expand(+ [+ ("no_prior_campaign", None, True),+ ("day_6_still_cooling", datetime(2026, 6, 25, 13, 0, tzinfo=UTC), False),+ ("day_7_exactly_over", datetime(2026, 6, 24, 12, 0, tzinfo=UTC), True),+ ]+ )+ def test_cooldown_boundary(self, _name: str, last_ended_at: datetime | None, expected: bool) -> None:+ assert is_cooldown_over(last_ended_at, NOW) is expected++ @parameterized.expand(+ [+ ("no_pin_always_due", None, True),+ ("today_due", date(2026, 7, 1), True),+ ("tomorrow_not_due", date(2026, 7, 2), False),+ ]+ )+ def test_pin_due(self, _name: str, scheduled_for: date | None, expected: bool) -> None:+ assert is_pin_due(scheduled_for, NOW) is expected++ @parameterized.expand(+ [+ ("day_89_still_cooling", datetime(2026, 4, 3, 13, 0, tzinfo=UTC), False),+ ("day_90_exactly_eligible", datetime(2026, 4, 2, 12, 0, tzinfo=UTC), True),+ ]+ )+ def test_retry_boundary(self, _name: str, ended_at: datetime, expected: bool) -> None:+ assert is_retry_eligible(ended_at, NOW) is expected++ def test_campaign_runs_14_days_from_its_own_start(self) -> None:+ assert campaign_ends_at(NOW) == datetime(2026, 7, 15, 12, 0, tzinfo=UTC)diff --git a/products/growth/backend/tests/test_product_push_selection.py b/products/growth/backend/tests/test_product_push_selection.pynew file mode 100644index 000000000000..04da657b9fd6--- /dev/null+++ b/products/growth/backend/tests/test_product_push_selection.py@@ -0,0 +1,159 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import BaseTest++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models.product_intent.product_intent import ProductIntent+from posthog.models.project import Project+from posthog.products import Products+from posthog.schema_enums import ProductItemCategory++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.cadence import SKIP_RETRY_DAYS+from products.growth.backend.product_push.selection import (+ BLESSED_PRODUCT_ORDER,+ FALLBACK_PRODUCT_ORDER,+ PUSH_PRODUCT_PATHS,+ select_next_product,+)++NOW = datetime(2026, 7, 1, 12, 0, tzinfo=UTC)+++class TestSelectNextProduct(BaseTest):+ def _campaign(self, product_key: str, status: str, **kwargs) -> ProductPushCampaign:+ return ProductPushCampaign.objects.create(+ organization=self.organization, product_key=product_key, status=status, **kwargs+ )++ def test_walks_blessed_order_from_the_top(self) -> None:+ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key == "product_analytics"+ assert selection.scheduled_campaign is None++ def test_activated_intent_excludes_checker_product_but_unactivated_does_not(self) -> None:+ # product_analytics has an activation criterion: only an *activated* intent counts as usage.+ intent = ProductIntent.objects.create(team=self.team, product_type="product_analytics")++ selection = select_next_product(self.organization, NOW)+ assert selection is not None+ assert selection.product_key == "product_analytics"++ intent.activated_at = NOW+ intent.save()++ selection = select_next_product(self.organization, NOW)+ assert selection is not None+ assert selection.product_key == "web_analytics"++ def test_any_intent_excludes_product_without_activation_criterion(self) -> None:+ # web_analytics has no activation criterion — a bare intent row is the usage signal.+ ProductIntent.objects.create(team=self.team, product_type="product_analytics", activated_at=NOW)+ ProductIntent.objects.create(team=self.team, product_type="web_analytics")++ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key == "session_replay"++ @parameterized.expand(+ [+ ("scheduled", ProductPushCampaign.Status.SCHEDULED, {"scheduled_for": (NOW + timedelta(days=30)).date()}),+ ("active", ProductPushCampaign.Status.ACTIVE, {"started_at": NOW - timedelta(days=5)}),+ ("adopted", ProductPushCampaign.Status.ADOPTED, {"ended_at": NOW - timedelta(days=200)}),+ ("recently_skipped", ProductPushCampaign.Status.SKIPPED, {"ended_at": NOW - timedelta(days=30)}),+ ("recently_cancelled", ProductPushCampaign.Status.CANCELLED, {"ended_at": NOW - timedelta(days=30)}),+ ]+ )+ def test_campaign_history_excludes_product_from_blessed_walk(self, _name: str, status: str, fields: dict) -> None:+ self._campaign("product_analytics", status, **fields)++ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key == "web_analytics"++ def test_skipped_product_retries_by_blessed_position_after_cooldown(self) -> None:+ # product_analytics was skipped >SKIP_RETRY_DAYS ago: eligible again, and blessed+ # position (not never-pushed-first) decides — it beats untried web_analytics.+ self._campaign(+ "product_analytics",+ ProductPushCampaign.Status.SKIPPED,+ ended_at=NOW - timedelta(days=SKIP_RETRY_DAYS + 1),+ )++ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key == "product_analytics"++ def test_product_used_in_a_minority_of_projects_is_still_pushed(self) -> None:+ _, second_team = Project.objects.create_with_team(+ initiating_user=None, organization=self.organization, name="second"+ )+ Project.objects.create_with_team(initiating_user=None, organization=self.organization, name="third")+ ProductIntent.objects.create(team=self.team, product_type="product_analytics", activated_at=NOW)++ selection = select_next_product(self.organization, NOW)+ assert selection is not None+ assert selection.product_key == "product_analytics"++ # A second project starts using it — now a majority (2 of 3) does, so it's excluded.+ ProductIntent.objects.create(team=second_team, product_type="product_analytics", activated_at=NOW)++ selection = select_next_product(self.organization, NOW)+ assert selection is not None+ assert selection.product_key == "web_analytics"++ def test_due_tam_rows_win_over_blessed_order_by_position(self) -> None:+ self._campaign("error_tracking", ProductPushCampaign.Status.SCHEDULED, position=1)+ self._campaign("surveys", ProductPushCampaign.Status.SCHEDULED, position=0)++ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key == "surveys"+ assert selection.scheduled_campaign is not None+ assert selection.scheduled_campaign.product_key == "surveys"++ def test_future_dated_pin_falls_through_to_blessed_order(self) -> None:+ self._campaign("surveys", ProductPushCampaign.Status.SCHEDULED, scheduled_for=(NOW + timedelta(days=10)).date())++ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key == "product_analytics"+ assert selection.scheduled_campaign is None++ def test_falls_back_to_the_random_pool_once_the_blessed_order_is_exhausted(self) -> None:+ for product_key in BLESSED_PRODUCT_ORDER:+ self._campaign(product_key.value, ProductPushCampaign.Status.ADOPTED, ended_at=NOW - timedelta(days=10))++ selection = select_next_product(self.organization, NOW)++ assert selection is not None+ assert selection.product_key in {product_key.value for product_key in FALLBACK_PRODUCT_ORDER}+ assert selection.scheduled_campaign is None++ def test_returns_none_when_every_pushable_product_is_excluded(self) -> None:+ for product_key in [*BLESSED_PRODUCT_ORDER, *FALLBACK_PRODUCT_ORDER]:+ self._campaign(product_key.value, ProductPushCampaign.Status.ADOPTED, ended_at=NOW - timedelta(days=10))++ assert select_next_product(self.organization, NOW) is None+++class TestPushProductConfig(SimpleTestCase):+ def test_every_pushable_product_resolves_to_a_released_catalog_item(self) -> None:+ # Guards against catalog drift: a key that doesn't resolve (or resolves to an+ # unreleased item) would render a broken or dead-end promo card.+ catalog = {product.path: product.category for product in Products.products()}+ for product_key in [*BLESSED_PRODUCT_ORDER, *FALLBACK_PRODUCT_ORDER]:+ path = PUSH_PRODUCT_PATHS.get(product_key)+ assert path is not None, f"{product_key} has no PUSH_PRODUCT_PATHS entry"+ assert path in catalog, f"{product_key} maps to {path!r}, which is not in the product catalog"+ assert catalog[path] != ProductItemCategory.UNRELEASED, f"{product_key} maps to unreleased {path!r}"diff --git a/products/growth/backend/tests/test_product_push_service.py b/products/growth/backend/tests/test_product_push_service.pynew file mode 100644index 000000000000..9f8724601d15--- /dev/null+++ b/products/growth/backend/tests/test_product_push_service.py@@ -0,0 +1,267 @@+from datetime import timedelta++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from posthog.models.organization import Organization+from posthog.models.product_intent.product_intent import ProductIntent++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.cadence import CAMPAIGN_DURATION_DAYS+from products.growth.backend.product_push.service import (+ cancel_campaigns,+ evaluate_and_close_campaign_batch,+ get_eligible_organization_queryset,+ start_campaigns_for_org_batch,+)+++class TestProductPushService(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.now = timezone.now()+ self._age_organization(self.organization, days=40)++ def _age_organization(self, organization: Organization, days: int) -> None:+ Organization.objects.filter(id=organization.id).update(created_at=self.now - timedelta(days=days))+ organization.refresh_from_db()++ def _active_campaign(self, product_key: str, started_days_ago: int = 5) -> ProductPushCampaign:+ started_at = self.now - timedelta(days=started_days_ago)+ return ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key=product_key,+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=started_at,+ ends_at=started_at + timedelta(days=CAMPAIGN_DURATION_DAYS),+ )++ # --- starting -----------------------------------------------------------++ def test_start_creates_active_campaign_and_rerun_is_a_noop(self) -> None:+ with patch("products.growth.backend.product_push.service.ph_scoped_capture") as mock_scoped:+ mock_capture = MagicMock()+ mock_scoped.return_value.__enter__.return_value = mock_capture+ result = start_campaigns_for_org_batch([str(self.organization.id)], self.now)++ assert result.started == 1+ campaign = ProductPushCampaign.objects.get(organization=self.organization)+ assert campaign.status == ProductPushCampaign.Status.ACTIVE+ assert campaign.product_key == "product_analytics"+ assert campaign.source == ProductPushCampaign.Source.AUTO+ assert campaign.started_at == self.now+ assert campaign.ends_at == self.now + timedelta(days=CAMPAIGN_DURATION_DAYS)+ assert mock_capture.call_args.kwargs["event"] == "product push campaign started"+ assert mock_capture.call_args.kwargs["distinct_id"] == str(self.organization.id)++ rerun = start_campaigns_for_org_batch([str(self.organization.id)], self.now)+ assert rerun.started == 0+ assert rerun.not_eligible == 1+ assert ProductPushCampaign.objects.filter(organization=self.organization).count() == 1++ def test_start_promotes_due_tam_row_instead_of_creating(self) -> None:+ scheduled = ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="surveys",+ status=ProductPushCampaign.Status.SCHEDULED,+ source=ProductPushCampaign.Source.TAM,+ )++ result = start_campaigns_for_org_batch([str(self.organization.id)], self.now)++ assert result.started == 1+ scheduled.refresh_from_db()+ assert scheduled.status == ProductPushCampaign.Status.ACTIVE+ assert scheduled.source == ProductPushCampaign.Source.TAM+ assert scheduled.started_at == self.now+ assert ProductPushCampaign.objects.filter(organization=self.organization).count() == 1++ def test_org_in_signup_grace_period_does_not_start(self) -> None:+ self._age_organization(self.organization, days=5)++ result = start_campaigns_for_org_batch([str(self.organization.id)], self.now)++ assert result.started == 0+ assert result.not_eligible == 1++ def test_cooldown_blocks_auto_start_but_due_dated_pin_bypasses_it(self) -> None:+ ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="session_replay",+ status=ProductPushCampaign.Status.SKIPPED,+ ended_at=self.now - timedelta(days=2),+ )++ result = start_campaigns_for_org_batch([str(self.organization.id)], self.now)+ assert result.started == 0+ assert result.not_eligible == 1++ ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="surveys",+ status=ProductPushCampaign.Status.SCHEDULED,+ source=ProductPushCampaign.Source.TAM,+ scheduled_for=self.now.date(),+ )++ result = start_campaigns_for_org_batch([str(self.organization.id)], self.now)+ assert result.started == 1+ assert (+ ProductPushCampaign.objects.get(+ organization=self.organization, status=ProductPushCampaign.Status.ACTIVE+ ).product_key+ == "surveys"+ )++ def test_dry_run_writes_nothing(self) -> None:+ result = start_campaigns_for_org_batch([str(self.organization.id)], self.now, dry_run=True)++ assert result.would_start == 1+ assert result.started == 0+ assert not ProductPushCampaign.objects.filter(organization=self.organization).exists()++ # --- closing ------------------------------------------------------------++ def test_activated_intent_during_campaign_closes_as_adopted(self) -> None:+ campaign = self._active_campaign("product_analytics")+ ProductIntent.objects.create(team=self.team, product_type="product_analytics", activated_at=self.now)++ result = evaluate_and_close_campaign_batch([str(campaign.id)], self.now)++ assert result.adopted == 1+ campaign.refresh_from_db()+ assert campaign.status == ProductPushCampaign.Status.ADOPTED+ assert campaign.ended_at == self.now+ assert campaign.metadata["adoption_signal"] == "intent_activated"+ assert campaign.metadata["adoption_team_id"] == self.team.id++ def test_activation_before_campaign_start_does_not_count(self) -> None:+ campaign = self._active_campaign("product_analytics", started_days_ago=5)+ intent = ProductIntent.objects.create(team=self.team, product_type="product_analytics")+ ProductIntent.objects.filter(id=intent.id).update(+ activated_at=self.now - timedelta(days=10), activation_last_checked_at=self.now+ )++ result = evaluate_and_close_campaign_batch([str(campaign.id)], self.now)++ assert result.adopted == 0+ campaign.refresh_from_db()+ assert campaign.status == ProductPushCampaign.Status.ACTIVE++ def test_expired_campaign_without_adoption_closes_as_skipped(self) -> None:+ campaign = self._active_campaign("product_analytics", started_days_ago=CAMPAIGN_DURATION_DAYS + 1)++ with patch("products.growth.backend.product_push.service.ph_scoped_capture") as mock_scoped:+ mock_capture = MagicMock()+ mock_scoped.return_value.__enter__.return_value = mock_capture+ result = evaluate_and_close_campaign_batch([str(campaign.id)], self.now)++ assert result.skipped == 1+ campaign.refresh_from_db()+ assert campaign.status == ProductPushCampaign.Status.SKIPPED+ assert campaign.ended_at == self.now+ assert mock_capture.call_args.kwargs["event"] == "product push campaign skipped"++ def test_intent_created_during_campaign_adopts_product_without_activation_criterion(self) -> None:+ campaign = self._active_campaign("web_analytics")+ ProductIntent.objects.create(team=self.team, product_type="web_analytics")++ result = evaluate_and_close_campaign_batch([str(campaign.id)], self.now)++ assert result.adopted == 1+ campaign.refresh_from_db()+ assert campaign.metadata["adoption_signal"] == "intent_created"++ def test_sweep_rechecks_stale_intents_so_quiet_activation_is_detected(self) -> None:+ campaign = self._active_campaign("product_analytics")+ ProductIntent.objects.create(team=self.team, product_type="product_analytics")++ def fake_check(intent: ProductIntent, skip_reporting: bool = False) -> bool:+ intent.activated_at = timezone.now()+ intent.save()+ return True++ with patch.object(ProductIntent, "check_and_update_activation", autospec=True, side_effect=fake_check):+ result = evaluate_and_close_campaign_batch([str(campaign.id)], self.now)++ assert result.adopted == 1+ campaign.refresh_from_db()+ assert campaign.status == ProductPushCampaign.Status.ADOPTED++ # --- eligibility query ----------------------------------------------------++ def test_eligible_organization_queryset_applies_grace_cooldown_and_pin_rules(self) -> None:+ young = Organization.objects.create(name="young")+ self._age_organization(young, days=5)++ with_active = Organization.objects.create(name="active")+ self._age_organization(with_active, days=40)+ ProductPushCampaign.objects.create(+ organization=with_active,+ product_key="surveys",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=self.now,+ )++ cooling = Organization.objects.create(name="cooling")+ self._age_organization(cooling, days=40)+ ProductPushCampaign.objects.create(+ organization=cooling,+ product_key="surveys",+ status=ProductPushCampaign.Status.SKIPPED,+ ended_at=self.now - timedelta(days=2),+ )++ cooling_with_pin = Organization.objects.create(name="cooling-with-pin")+ self._age_organization(cooling_with_pin, days=40)+ ProductPushCampaign.objects.create(+ organization=cooling_with_pin,+ product_key="surveys",+ status=ProductPushCampaign.Status.SKIPPED,+ ended_at=self.now - timedelta(days=2),+ )+ ProductPushCampaign.objects.create(+ organization=cooling_with_pin,+ product_key="error_tracking",+ status=ProductPushCampaign.Status.SCHEDULED,+ scheduled_for=self.now.date(),+ )++ internal = Organization.objects.create(name="internal", for_internal_metrics=True)+ self._age_organization(internal, days=40)++ eligible_ids = set(get_eligible_organization_queryset(self.now).values_list("id", flat=True))++ assert self.organization.id in eligible_ids+ assert cooling_with_pin.id in eligible_ids+ assert young.id not in eligible_ids+ assert with_active.id not in eligible_ids+ assert cooling.id not in eligible_ids+ assert internal.id not in eligible_ids++ # --- cancelling -----------------------------------------------------------++ def test_cancel_only_touches_scheduled_and_active_rows(self) -> None:+ active = self._active_campaign("product_analytics")+ scheduled = ProductPushCampaign.objects.create(+ organization=self.organization, product_key="surveys", status=ProductPushCampaign.Status.SCHEDULED+ )+ adopted = ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="web_analytics",+ status=ProductPushCampaign.Status.ADOPTED,+ ended_at=self.now - timedelta(days=1),+ )++ cancelled_count = cancel_campaigns([str(active.id), str(scheduled.id), str(adopted.id)], self.now)++ assert cancelled_count == 2+ active.refresh_from_db()+ scheduled.refresh_from_db()+ adopted.refresh_from_db()+ assert active.status == ProductPushCampaign.Status.CANCELLED+ assert active.ended_at == self.now+ assert scheduled.status == ProductPushCampaign.Status.CANCELLED+ assert adopted.status == ProductPushCampaign.Status.ADOPTEDdiff --git a/products/growth/dags/product_push_campaigns.py b/products/growth/dags/product_push_campaigns.pynew file mode 100644index 000000000000..7f757231be4c--- /dev/null+++ b/products/growth/dags/product_push_campaigns.py@@ -0,0 +1,266 @@+"""Daily Dagster job driving organization product push campaigns.++Two sequenced phases:++1. Close — evaluate every ACTIVE campaign: close as adopted when the org started+ using the product, as skipped when the 14-day window expired without adoption.+2. Start — start the next campaign for every eligible org (past the signup grace+ period, no active campaign, out of the between-campaigns cooldown, or holding a+ due dated TAM pin).++The start phase depends on the collected close results so a campaign that expires+today frees its org for cadence evaluation in the same run (the cooldown then+keeps it quiet for 7 days).++All business logic lives in products/growth/backend/product_push/; this file only+orchestrates. Rollout controls (`rollout_percentage`, `max_starts`, `dry_run`)+exist for the first supervised runs: on day one every org older than the grace+period is eligible at once, so ramp gradually to stagger cadence phases across+the fleet.+"""++import hashlib+from dataclasses import dataclass+from datetime import UTC, datetime++from django.conf import settings+from django.db import connections++import dagster+import pydantic++from posthog.clickhouse.query_tagging import get_query_tags+from posthog.dags.common import JobOwners, dagster_tags, skip_if_already_running+from posthog.exceptions_capture import capture_exception++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.service import (+ CloseBatchResult,+ StartBatchResult,+ evaluate_and_close_campaign_batch,+ get_eligible_organization_queryset,+ start_campaigns_for_org_batch,+)++SWEEP_BATCH_SIZE = 500++_BATCH_OP_RETRY_POLICY = dagster.RetryPolicy(+ max_retries=3,+ delay=30,+ backoff=dagster.Backoff.EXPONENTIAL,+ jitter=dagster.Jitter.FULL,+)+++@dataclass(kw_only=True)+class StartBatchSpec:+ organization_ids: list[str]+ dry_run: bool+++class StartSweepConfig(dagster.Config):+ """Config for the start phase of the product push campaign job."""++ organization_ids: list[str] = pydantic.Field(+ default=[],+ description="Only consider these organization ids (UUIDs). Empty = all eligible organizations.",+ )+ batch_size: int = pydantic.Field(default=SWEEP_BATCH_SIZE, gt=0)+ rollout_percentage: float = pydantic.Field(+ default=1.0,+ ge=0.0,+ le=1.0,+ description="Deterministic per-org rollout fraction (sha256 over the org id, monotonic across runs).",+ )+ max_starts: int | None = pydantic.Field(+ default=None,+ description="Cap on how many organizations may start a campaign this run (herd control for early runs).",+ gt=0,+ )+ dry_run: bool = pydantic.Field(+ default=False,+ description="Log what would start without writing campaigns or emitting events.",+ )+++def _org_in_rollout(organization_id: str, rollout_percentage: float) -> bool:+ if rollout_percentage >= 1.0:+ return True+ bucket = int(hashlib.sha256(organization_id.encode()).hexdigest(), 16) % 100_000+ return bucket < rollout_percentage * 100_000++[email protected](out=dagster.DynamicOut(list[str]))+def get_active_campaign_batches_op(context: dagster.OpExecutionContext):+ """Fan out every ACTIVE campaign id as batches for the close phase.++ Always yields at least one (possibly empty) batch so the downstream collect —+ and with it the whole start phase — runs even on days with zero active+ campaigns (e.g. the very first run).+ """+ campaign_ids = [+ str(campaign_id)+ for campaign_id in ProductPushCampaign.objects.filter(status=ProductPushCampaign.Status.ACTIVE).values_list(+ "id", flat=True+ )+ ]+ context.log.info(f"Found {len(campaign_ids)} active campaigns to evaluate")++ if not campaign_ids:+ yield dagster.DynamicOutput([], mapping_key="batch_0")+ return+ for index in range(0, len(campaign_ids), SWEEP_BATCH_SIZE):+ yield dagster.DynamicOutput(+ campaign_ids[index : index + SWEEP_BATCH_SIZE], mapping_key=f"batch_{index // SWEEP_BATCH_SIZE}"+ )++[email protected](retry_policy=_BATCH_OP_RETRY_POLICY)+def evaluate_campaign_batch_op(context: dagster.OpExecutionContext, campaign_ids: list[str]) -> CloseBatchResult:+ """Adopt / skip the campaigns in this batch. Retry-safe: transitions run under+ SKIP LOCKED with a status filter, so a retried batch is a no-op for rows the+ first attempt already closed."""+ get_query_tags().with_dagster(dagster_tags(context))+ try:+ result = evaluate_and_close_campaign_batch(campaign_ids, now=datetime.now(tz=UTC))+ context.log.info(+ f"Batch of {len(campaign_ids)}: {result.evaluated} evaluated, "+ f"{result.adopted} adopted, {result.skipped} skipped"+ )+ return result+ except Exception as e:+ context.log.exception(f"Failed to evaluate batch of {len(campaign_ids)} campaigns")+ capture_exception(e, {"team": "team-growth", "campaign_count": len(campaign_ids)})+ raise+ finally:+ if not settings.TEST:+ connections.close_all()++[email protected](out=dagster.DynamicOut(StartBatchSpec))+def get_eligible_org_batches_op(+ context: dagster.OpExecutionContext,+ config: StartSweepConfig,+ close_results: list[CloseBatchResult],+):+ """Fan out eligible organization ids as batches for the start phase.++ Takes the collected close results as input purely for sequencing: starts must+ observe the campaigns this run just closed.+ """+ context.log.info(+ f"Close phase done ({sum(r.evaluated for r in close_results)} campaigns evaluated); computing eligible orgs"+ )++ queryset = get_eligible_organization_queryset(datetime.now(tz=UTC)).order_by("created_at")+ if config.organization_ids:+ queryset = queryset.filter(id__in=config.organization_ids)++ organization_ids = [str(organization_id) for organization_id in queryset.values_list("id", flat=True)]+ total_eligible = len(organization_ids)++ if config.rollout_percentage < 1.0:+ organization_ids = [+ organization_id+ for organization_id in organization_ids+ if _org_in_rollout(organization_id, config.rollout_percentage)+ ]+ if config.max_starts is not None:+ organization_ids = organization_ids[: config.max_starts]++ context.log.info(+ f"{total_eligible} orgs eligible, {len(organization_ids)} selected "+ f"(rollout={config.rollout_percentage}, max_starts={config.max_starts}, dry_run={config.dry_run})"+ )++ if not organization_ids:+ yield dagster.DynamicOutput(StartBatchSpec(organization_ids=[], dry_run=config.dry_run), mapping_key="batch_0")+ return+ for index in range(0, len(organization_ids), config.batch_size):+ yield dagster.DynamicOutput(+ StartBatchSpec(+ organization_ids=organization_ids[index : index + config.batch_size], dry_run=config.dry_run+ ),+ mapping_key=f"batch_{index // config.batch_size}",+ )++[email protected](retry_policy=_BATCH_OP_RETRY_POLICY)+def start_campaign_batch_op(context: dagster.OpExecutionContext, spec: StartBatchSpec) -> StartBatchResult:+ """Start campaigns for the orgs in this batch. Retry-safe: eligibility is+ re-checked per org and the one-active-per-org partial unique constraint turns+ a concurrent double-start into a counted conflict."""+ get_query_tags().with_dagster(dagster_tags(context))+ try:+ result = start_campaigns_for_org_batch(spec.organization_ids, now=datetime.now(tz=UTC), dry_run=spec.dry_run)+ context.log.info(+ f"Batch of {result.orgs_processed} orgs: {result.started} started, {result.would_start} would start, "+ f"{result.no_candidate} without candidate, {result.not_eligible} not eligible, "+ f"{result.conflicts} conflicts"+ )+ return result+ except Exception as e:+ context.log.exception(f"Failed to start campaigns for batch of {len(spec.organization_ids)} orgs")+ capture_exception(e, {"team": "team-growth", "org_count": len(spec.organization_ids)})+ raise+ finally:+ if not settings.TEST:+ connections.close_all()+++def summarize_product_push_run_op(+ context: dagster.OpExecutionContext,+ close_results: list[CloseBatchResult],+ start_results: list[StartBatchResult],+) -> None:+ """Roll up per-batch counts into a single run-level summary."""+ adopted = sum(r.adopted for r in close_results)+ skipped = sum(r.skipped for r in close_results)+ started = sum(r.started for r in start_results)+ would_start = sum(r.would_start for r in start_results)++ context.log.info(+ f"Run complete: {adopted} adopted, {skipped} skipped, {started} started, {would_start} would start"+ )+ context.add_output_metadata(+ {+ "campaigns_evaluated": dagster.MetadataValue.int(sum(r.evaluated for r in close_results)),+ "campaigns_adopted": dagster.MetadataValue.int(adopted),+ "campaigns_skipped": dagster.MetadataValue.int(skipped),+ "orgs_processed": dagster.MetadataValue.int(sum(r.orgs_processed for r in start_results)),+ "campaigns_started": dagster.MetadataValue.int(started),+ "campaigns_would_start": dagster.MetadataValue.int(would_start),+ "starts_not_eligible": dagster.MetadataValue.int(sum(r.not_eligible for r in start_results)),+ "starts_no_candidate": dagster.MetadataValue.int(sum(r.no_candidate for r in start_results)),+ "start_conflicts": dagster.MetadataValue.int(sum(r.conflicts for r in start_results)),+ }+ )+++ description=(+ "Daily job driving organization product push campaigns: closes active campaigns "+ "(adopted / skipped) and starts the next campaign for eligible organizations."+ ),+ executor_def=dagster.multiprocess_executor.configured({"max_concurrent": 5}),+ tags={"owner": JobOwners.TEAM_GROWTH.value},+)+def product_push_campaigns_job():+ close_results = get_active_campaign_batches_op().map(evaluate_campaign_batch_op).collect()+ start_results = get_eligible_org_batches_op(close_results).map(start_campaign_batch_op).collect()+ summarize_product_push_run_op(close_results, start_results)+++ job=product_push_campaigns_job,+ cron_schedule="0 6 * * *",+ execution_timezone="UTC",+ default_status=dagster.DefaultScheduleStatus.STOPPED,+)+@skip_if_already_running+def product_push_campaigns_schedule(context: dagster.ScheduleEvaluationContext):+ # Never stack runs: overlapping sweeps are transition-safe (SKIP LOCKED ++ # unique constraint) but would double-scan every org and double-check+ # adoption for nothing.+ return dagster.RunRequest()diff --git a/products/growth/dags/tests/test_product_push_campaigns.py b/products/growth/dags/tests/test_product_push_campaigns.pynew file mode 100644index 000000000000..375de14b4d46--- /dev/null+++ b/products/growth/dags/tests/test_product_push_campaigns.py@@ -0,0 +1,88 @@+from contextlib import contextmanager+from datetime import timedelta+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from posthog.models.organization import Organization++from products.growth.backend.models import ProductPushCampaign+from products.growth.backend.product_push.cadence import CAMPAIGN_DURATION_DAYS+from products.growth.dags.product_push_campaigns import product_push_campaigns_job+++@contextmanager+def _mock_capture():+ capture_fn: Any = MagicMock()+ with patch("products.growth.backend.product_push.service.ph_scoped_capture") as mock_csm:+ mock_csm.return_value.__enter__.return_value = capture_fn+ mock_csm.return_value.__exit__.return_value = False+ yield capture_fn+++class TestProductPushCampaignsJob(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self._age_organization(self.organization, days=40)++ def _age_organization(self, organization: Organization, days: int) -> None:+ Organization.objects.filter(id=organization.id).update(created_at=timezone.now() - timedelta(days=days))++ def _run_job(self, start_config: dict | None = None) -> Any:+ run_config = {"ops": {"get_eligible_org_batches_op": {"config": start_config}}} if start_config else None+ with _mock_capture():+ return product_push_campaigns_job.execute_in_process(run_config=run_config)++ def test_first_run_with_no_active_campaigns_still_starts_for_eligible_org(self) -> None:+ result = self._run_job()++ assert result.success+ campaign = ProductPushCampaign.objects.get(organization=self.organization)+ assert campaign.status == ProductPushCampaign.Status.ACTIVE+ assert campaign.product_key == "product_analytics"++ def test_expired_campaign_is_skipped_and_cooldown_blocks_a_same_run_restart(self) -> None:+ started_at = timezone.now() - timedelta(days=CAMPAIGN_DURATION_DAYS + 1)+ campaign = ProductPushCampaign.objects.create(+ organization=self.organization,+ product_key="product_analytics",+ status=ProductPushCampaign.Status.ACTIVE,+ started_at=started_at,+ ends_at=started_at + timedelta(days=CAMPAIGN_DURATION_DAYS),+ )++ result = self._run_job()++ assert result.success+ campaign.refresh_from_db()+ assert campaign.status == ProductPushCampaign.Status.SKIPPED+ assert not ProductPushCampaign.objects.filter(+ organization=self.organization, status=ProductPushCampaign.Status.ACTIVE+ ).exists()++ def test_dry_run_and_zero_rollout_write_nothing(self) -> None:+ result = self._run_job({"dry_run": True})+ assert result.success+ assert not ProductPushCampaign.objects.exists()++ result = self._run_job({"rollout_percentage": 0.0})+ assert result.success+ assert not ProductPushCampaign.objects.exists()++ def test_organization_ids_override_and_max_starts_cap(self) -> None:+ other = Organization.objects.create(name="other")+ self._age_organization(other, days=40)++ result = self._run_job({"organization_ids": [str(other.id)]})+ assert result.success+ assert not ProductPushCampaign.objects.filter(organization=self.organization).exists()+ assert ProductPushCampaign.objects.filter(organization=other).count() == 1++ ProductPushCampaign.objects.all().delete()++ result = self._run_job({"max_starts": 1})+ assert result.success+ assert ProductPushCampaign.objects.filter(status=ProductPushCampaign.Status.ACTIVE).count() == 1diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.tsindex 90c4b44212ef..19a8b023d9c1 100644--- a/products/growth/frontend/generated/api.schemas.ts+++ b/products/growth/frontend/generated/api.schemas.ts@@ -7,6 +7,30 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface ProductPushCampaignApi {+ /** Campaign id. Stable for the campaign's lifetime — key per-user dismissal state on it. */+ readonly id: string+ /** ProductKey value of the product being pushed (e.g. 'session_replay'). */+ readonly product_key: string+ /**+ * Sidebar path of the pushed product in the product catalog, for display resolution. Null when the key maps to no released catalog item.+ * @nullable+ */+ readonly product_path: string | null+ /**+ * Custom promo copy written by the TAM. Null means the client should use its default copy.+ * @nullable+ */+ readonly reason_text: string | null+ /** When this campaign started. */+ readonly started_at: string+ /**+ * When this campaign is planned to end.+ * @nullable+ */+ readonly ends_at: string | null+}+/*** * `high` - high* * `medium` - medium@@ -206,6 +230,13 @@ export interface IdentityMatchingRunsResponseApi {results: IdentityMatchingRunApi[]}+export type ProductPushCampaignActiveRetrieveParams = {+ /**+ * Team id of the project the caller is viewing. When that project already uses the campaign's product, the response is 204 so the promo isn't shown there.+ */+ team_id?: number+}+export type IdentityMatchingLinksListParams = {/*** Identity matching run to read. Defaults to the team's most recent run.diff --git a/products/growth/frontend/generated/api.ts b/products/growth/frontend/generated/api.tsindex 8f63b5dff333..521037dc1f31 100644--- a/products/growth/frontend/generated/api.ts+++ b/products/growth/frontend/generated/api.ts@@ -12,8 +12,43 @@ import type {IdentityMatchingLinksListParams,IdentityMatchingLinksResponseApi,IdentityMatchingRunsResponseApi,+ ProductPushCampaignActiveRetrieveParams,+ ProductPushCampaignApi,} from './api.schemas'+export const getProductPushCampaignActiveRetrieveUrl = (+ organizationId: string,+ params?: ProductPushCampaignActiveRetrieveParams+) => {+ 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}/product_push_campaign/active/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/product_push_campaign/active/`+}++/**+ * The organization's currently active product push campaign. 204 when no campaign is active, or when the given project already uses the campaign's product.+ */+export const productPushCampaignActiveRetrieve = async (+ organizationId: string,+ params?: ProductPushCampaignActiveRetrieveParams,+ options?: RequestInit+): Promise<ProductPushCampaignApi | void> => {+ return apiMutator<ProductPushCampaignApi | void>(getProductPushCampaignActiveRetrieveUrl(organizationId, params), {+ ...options,+ method: 'GET',+ })+}+export const getIdentityMatchingLinksListUrl = (projectId: string, params?: IdentityMatchingLinksListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/growth/frontend/generated/api.zod.schemas.ts b/products/growth/frontend/generated/api.zod.schemas.tsindex 13e88ba0982f..6e83574e060b 100644--- a/products/growth/frontend/generated/api.zod.schemas.ts+++ b/products/growth/frontend/generated/api.zod.schemas.ts@@ -9,6 +9,26 @@*/import { z as zod } from 'zod'+export const ProductPushCampaignApi = zod.object({+ id: zod.uuid().describe("Campaign id. Stable for the campaign's lifetime — key per-user dismissal state on it."),+ product_key: zod.string().describe("ProductKey value of the product being pushed (e.g. 'session_replay')."),+ product_path: zod+ .string()+ .nullable()+ .describe(+ 'Sidebar path of the pushed product in the product catalog, for display resolution. Null when the key maps to no released catalog item.'+ ),+ reason_text: zod+ .string()+ .nullable()+ .describe('Custom promo copy written by the TAM. Null means the client should use its default copy.'),+ started_at: zod.iso.datetime({ offset: true }).describe('When this campaign started.'),+ ends_at: zod.iso.datetime({ offset: true }).nullable().describe('When this campaign is planned to end.'),+})++export type ProductPushCampaignApi = zod.input<typeof ProductPushCampaignApi>+export type ProductPushCampaignApiOutput = zod.output<typeof ProductPushCampaignApi>+export const TierEnumApi = zod.enum(['high', 'medium', 'low']).describe('\* `high` - high\n\* `medium` - medium\n\* `low` - low')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c31d3e8c07cb..542f09bea262 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44067,6 +44067,30 @@ export namespace Schemas {created_at: string | null;}+ export interface ProductPushCampaign {+ /** Campaign id. Stable for the campaign's lifetime — key per-user dismissal state on it. */+ readonly id: string;+ /** ProductKey value of the product being pushed (e.g. 'session_replay'). */+ readonly product_key: string;+ /**+ * Sidebar path of the pushed product in the product catalog, for display resolution. Null when the key maps to no released catalog item.+ * @nullable+ */+ readonly product_path: string | null;+ /**+ * Custom promo copy written by the TAM. Null means the client should use its default copy.+ * @nullable+ */+ readonly reason_text: string | null;+ /** When this campaign started. */+ readonly started_at: string;+ /**+ * When this campaign is planned to end.+ * @nullable+ */+ readonly ends_at: string | null;+ }+/*** Serializer for creating and updating ProductTour.*/@@ -61912,6 +61936,13 @@ export namespace Schemas {offset?: number;};+ export type ProductPushCampaignActiveRetrieveParams = {+ /**+ * Team id of the project the caller is viewing. When that project already uses the campaign's product, the response is 204 so the promo isn't shown there.+ */+ team_id?: number;+ };+export type OrganizationsProjectsListParams = {/*** Number of results to return per page.diff --git a/tach.toml b/tach.tomlindex 5934472bad17..9aa923c8074d 100644--- a/tach.toml+++ b/tach.toml@@ -366,6 +366,7 @@ layer = "modules"[[modules]]path = "products.growth"depends_on = [+ "ee","posthog",]layer = "modules"