: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(marketing-analytics): announce new ad sources (#107756)
Javier Bahamondesa427285bd76e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ad5ba9834abc..3e7485b8e936 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5556,6 +5556,22 @@ snapshots:hash: v1.k794b7964.f9059da612f8cb309c1100982a7352bf0c010c585701ed9f703ed1962da1a8b2.4Wbe0lwcRKZju4mbcJDVTwzvT2DtSSqF1VwdFStAA5ologs-logsretentionperiodpicker--stored-custom-months-without-paid-retention--light:hash: v1.k794b7964.d8d79824779beb9150246c932e4f2b756133d02aca4ca269271b98d0e9082480.PCD7I0jw8Fis5NRmUgRrjvUpwz5Dap-BO1UKMSJu5Ns+ marketing-analytics-add-source--dismissed-everywhere--dark:+ hash: v1.k794b7964.f23fe271dbeafe8d745237090a5a115e167653cdb000e74a3245efd986450ff0.ymRCgme2xTcwSDlK8Mjxj_zM6bDHbYjLGl0ncGYQfuo+ marketing-analytics-add-source--dismissed-everywhere--light:+ hash: v1.k794b7964.12d8d6d7eae501b0994d4df904e55fcead99c2754c093f2566f1ff7a67e4c106.bG0Lzy9eInVPGg_qrd0_QbxO0cFb3p5lasyED9iwE_I+ marketing-analytics-add-source--new-sources--dark:+ hash: v1.k794b7964.705f97d369b1d9ad70b9276f45ecb9c46d637d117257ba42c7787fcab02ec5f6.RrWX7Yl8HSHJ0loJUUU58364Daew7QTlYI88OLS-U20+ marketing-analytics-add-source--new-sources--light:+ hash: v1.k794b7964.5fa1307763c5b2c1d15d9da94126801e790cdb76e0d0de4e7afcd9cd27bc4c50.vlfBEVR6C5WxdqBMZe2QoAmr_I-A-oivfeAPBPrwLzc+ marketing-analytics-add-source--open-menu--dark:+ hash: v1.k794b7964.72c67ad4702a042b6eb027ad30e6cafca8c414be1b22cdb28b7a62ae16a0d684.NS37A7XjVATW1ezz9bQ0Jra_r4iL_F3eYCgggWr0FYU+ marketing-analytics-add-source--open-menu--light:+ hash: v1.k794b7964.a0f071a6ec0fd5fe906994d405ec2dbb9338f52e8a09cbe1e574b6a2301150b6.65yXO6LAE3bw8Rqg_BLEQoZZxPW_yEyWh4ipVUFvxV0+ marketing-analytics-add-source--sources-disabled--dark:+ hash: v1.k794b7964.6ab679994aa458fc15fd650db178bf805d878d726265ad51e3502d9029e63903.z12MB5eLM0VM1Bs8-v2_5d5HH5VaDT25r8GuqvBC4ds+ marketing-analytics-add-source--sources-disabled--light:+ hash: v1.k794b7964.a40f8610ed453a1401dbbc1fb3bb921eeb3f55656138dc3e26b4751f6e38b7e8.0Ura8ZyXPrrQdqAbS1DDqkmoEZMPWEe4Y5EcDqQ39Xkmarketing-analytics-customer-acquisition-cards--configuration-loading--dark:hash: v1.k794b7964.4e3295796230b8ccc9ce5cb239d9ffe000af9d00324d31584d3fa6fde8550fe9.04jR2iHz7Mn5n3Z6KmK4yt-R520UGYL9im_4Icykhxkmarketing-analytics-customer-acquisition-cards--configuration-loading--light:diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/AddIntegrationButton.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/AddIntegrationButton.tsxdeleted file mode 100644index f67b71322509..000000000000--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/AddIntegrationButton.tsx+++ /dev/null@@ -1,115 +0,0 @@-import { useValues } from 'kea'-import { router } from 'kea-router'-import { useState } from 'react'--import { IconPlusSmall } from '@posthog/icons'-import { LemonButton, LemonDropdown } from '@posthog/lemon-ui'--import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { urls } from 'scenes/urls'--import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'--import {- VALID_NON_NATIVE_MARKETING_SOURCES,- VALID_SELF_MANAGED_MARKETING_SOURCES,- getEnabledNativeMarketingSources,-} from '../../logic/utils'--interface AddIntegrationButtonProps {- onIntegrationSelect?: (integrationId: string) => void-}--export function AddIntegrationButton({ onIntegrationSelect }: AddIntegrationButtonProps = {}): JSX.Element {- const { featureFlags } = useValues(featureFlagLogic)- const restrictedReason = useRestrictedArea({- scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,- })-- const [showPopover, setShowPopover] = useState(false)-- const groupedIntegrations = {- native: getEnabledNativeMarketingSources(featureFlags),- external: VALID_NON_NATIVE_MARKETING_SOURCES,- 'self-managed': VALID_SELF_MANAGED_MARKETING_SOURCES,- }-- const handleIntegrateClick = (integrationId: string): void => {- if (onIntegrationSelect) {- onIntegrationSelect(integrationId)- } else {- router.actions.push(- urls.dataWarehouseSourceNew(integrationId, urls.marketingAnalyticsApp(), 'Marketing analytics')- )- }- setShowPopover(false)- }-- const renderIntegrationGroup = (- type: string,- integrations: readonly string[],- title: string- ): JSX.Element | null => {- if (integrations.length === 0) {- return null- }-- return (- <div key={type}>- <div className="px-2 py-1 text-xs font-medium text-muted-foreground">{title}</div>- {integrations.map((integrationId) => (- <LemonButton- key={integrationId}- fullWidth- size="small"- disabledReason={restrictedReason}- onClick={() => handleIntegrateClick(integrationId)}- className="justify-start"- >- <span className="flex items-center gap-2">- <SourceIcon type={integrationId} size="xsmall" disableTooltip />- <span className="flex flex-col items-start">- <span className="font-medium">{integrationId}</span>- </span>- </span>- </LemonButton>- ))}- </div>- )- }-- return (- <LemonDropdown- closeOnClickInside={false}- visible={showPopover}- matchWidth={false}- actionable- onVisibilityChange={setShowPopover}- overlay={- <div className="max-w-80 space-y-px p-1">- <div className="px-2 py-1 text-xs text-muted-foreground font-bold">Connect new data source</div>- {renderIntegrationGroup('native', groupedIntegrations.native, 'Native integrations')}- {renderIntegrationGroup('external', groupedIntegrations.external, 'External sources')}- {renderIntegrationGroup(- 'self-managed',- groupedIntegrations['self-managed'],- 'Self-managed sources'- )}- </div>- }- >- <LemonButton- type="primary"- size="small"- icon={<IconPlusSmall />}- data-attr="add-integration"- disabledReason={restrictedReason}- >- Add source- </LemonButton>- </LemonDropdown>- )-}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsxindex 758442ab010b..d7d548f0f0bc 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx@@ -18,9 +18,10 @@ import { teamLogic } from 'scenes/teamLogic'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'import { ReloadAll } from '~/queries/nodes/DataNode/Reload'+import { AddIntegrationButton } from 'products/marketing_analytics/frontend/components/AddIntegrationButton'+import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from '../../logic/marketingAnalyticsTilesLogic'-import { AddIntegrationButton } from './AddIntegrationButton'import { ConversionGoalFilterButton } from './ConversionGoalFilterButton'import { ConversionGoalModal } from './ConversionGoalModal'import { IntegrationFilter } from './IntegrationFilter'diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ExternalDataSourceConfiguration.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ExternalDataSourceConfiguration.tsxindex 1dd5e485968c..67bc23e97bb4 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ExternalDataSourceConfiguration.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ExternalDataSourceConfiguration.tsx@@ -18,6 +18,7 @@ import {import { ExternalDataSchemaStatus, ExternalDataSource, ManualLinkSourceType } from '~/types'import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'+import { AddIntegrationButton } from 'products/marketing_analytics/frontend/components/AddIntegrationButton'import { useSortedPaginatedList } from '../../hooks/useSortedPaginatedList'import {@@ -36,7 +37,6 @@ import {findSchemaByFieldName,nativeSourceDisplayLabel,} from '../../logic/utils'-import { AddIntegrationButton } from '../MarketingAnalyticsFilters/AddIntegrationButton'import { ColumnMappingModal } from './ColumnMappingModal'import { ListDisplay } from './ListDisplay'import { ItemName, PaginationControls } from './PaginationControls'diff --git a/products/marketing_analytics/frontend/components/AddIntegrationButton.stories.tsx b/products/marketing_analytics/frontend/components/AddIntegrationButton.stories.tsxnew file mode 100644index 000000000000..b9ebaed08884--- /dev/null+++ b/products/marketing_analytics/frontend/components/AddIntegrationButton.stories.tsx@@ -0,0 +1,152 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import type { Meta, StoryObj } from '@storybook/react'+import { useValues } from 'kea'+import { useEffect } from 'react'++import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { mswDecorator } from '~/mocks/browser'++import { expect, userEvent, waitFor, within } from 'storybook/test'++import { AddIntegrationButton } from './AddIntegrationButton'+import { NEW_AD_SOURCES_SEEN_KEY } from './newAdSourcesLogic'++function SourceButtons(): JSX.Element {+ const { user } = useValues(userLogic)+ useEffect(() => {+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, has_seen_product_intro_for: {} })+ }, [])+ return (+ <div className="w-120 max-w-full min-h-40 p-4 space-y-12" data-attr="add-source-buttons">+ {user &&+ ['Dashboard', 'Setup'].map((label) => (+ <div key={label} className="flex items-center justify-between gap-4">+ <span className="font-semibold">{label}</span>+ <AddIntegrationButton />+ </div>+ ))}+ </div>+ )+}++const meta: Meta<typeof AddIntegrationButton> = {+ title: 'Marketing Analytics/Add source',+ component: AddIntegrationButton,+ render: () => <SourceButtons />,+ decorators: [+ mswDecorator({+ patch: {+ '/api/users/@me/product_intro_seen': [200, { [NEW_AD_SOURCES_SEEN_KEY]: true }],+ },+ get: {+ '/api/environments/:team_id/external_data_sources/wizard': [+ 200,+ Object.fromEntries(+ Object.entries({+ GoogleAds: 'google-ads.png',+ LinkedinAds: 'linkedin.png',+ MetaAds: 'meta-ads.png',+ TikTokAds: 'tiktok.png',+ RedditAds: 'reddit.png',+ BingAds: 'bing-ads.svg',+ SnapchatAds: 'snapchat.png',+ PinterestAds: 'pinterest_ads.png',+ AppleSearchAds: 'apple_search_ads.png',+ OpenAIAds: 'openai_ads.svg',+ AmazonAds: 'amazon_ads.png',+ BigQuery: 'bigquery.png',+ }).map(([name, icon]) => [+ name,+ { name, caption: name, iconPath: `/static/services/${icon}`, fields: [] },+ ])+ ),+ ],+ '/api/users/@me/': [200, { ...MOCK_DEFAULT_USER, has_seen_product_intro_for: {} }],+ },+ }),+ ],+ parameters: {+ featureFlags: [+ FEATURE_FLAGS.MARKETING_ANALYTICS_APPLE_ADS,+ FEATURE_FLAGS.MARKETING_ANALYTICS_OPENAI_ADS,+ FEATURE_FLAGS.MARKETING_ANALYTICS_AMAZON_ADS,+ ],+ testOptions: { viewport: { width: 520, height: 1024 } },+ },+}+export default meta+type Story = StoryObj<typeof AddIntegrationButton>++export const NewSources: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const body = within(canvasElement.ownerDocument.body)+ await waitFor(() => expect(canvas.getAllByText('New')).toHaveLength(2))+ const team = teamLogic.values.currentTeam!+ teamLogic.actions.loadCurrentTeamSuccess({+ ...team,+ effective_membership_level: OrganizationMembershipLevel.Member,+ })+ await waitFor(() => expect(canvas.queryAllByText('New')).toHaveLength(0))+ await userEvent.hover(canvas.getAllByText('Add source')[0])+ await body.findByText(/This area is restricted to project admins/)+ expect(body.queryByText('New ad sources are available')).not.toBeInTheDocument()+ await userEvent.unhover(canvas.getAllByText('Add source')[0])+ teamLogic.actions.loadCurrentTeamSuccess(team)+ await waitFor(() => expect(canvas.getAllByText('New')).toHaveLength(2))+ expect(canvas.getAllByText('Add source')[0].closest('button')).toHaveAccessibleName('Add source')+ await userEvent.hover(canvas.getAllByText('Add source')[0])+ await body.findByText('New ad sources are available')+ },+}++export const OpenMenu: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await waitFor(() => expect(canvas.getAllByText('New')).toHaveLength(2))+ await userEvent.click(canvas.getAllByText('Add source')[0])+ const body = within(canvasElement.ownerDocument.body)+ await body.findByText('New ad sources')+ expect(body.queryByText('Got it')).not.toBeInTheDocument()+ await waitFor(() => expect(canvas.queryAllByText('New')).toHaveLength(0))+ await userEvent.keyboard('{ArrowDown}')+ const googleAds = body.getByText('Google Ads').closest('a')!+ expect(googleAds).toHaveAttribute('href', expect.stringContaining('GoogleAds'))+ await waitFor(() => expect(googleAds).toHaveFocus())+ await userEvent.click(body.getByText('New ad sources'))+ },+}++export const DismissedEverywhere: Story = {+ parameters: { testOptions: { snapshotTargetSelector: '[data-attr="add-source-buttons"]' } },+ play: async (context) => {+ await OpenMenu.play!(context)+ const canvas = within(context.canvasElement)+ const body = within(context.canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByText('Dashboard'))+ await waitFor(() => expect(body.queryByText('New ad sources')).not.toBeInTheDocument())+ await waitFor(() => expect(body.queryAllByText(/^new$/i)).toHaveLength(0))+ await userEvent.click(canvas.getAllByText('Add source')[1])+ await body.findByText('Native integrations')+ expect(body.queryByText('New ad sources')).not.toBeInTheDocument()+ expect(body.queryAllByText(/^new$/i)).toHaveLength(0)+ await userEvent.click(canvas.getByText('Setup'))+ await waitFor(() => expect(body.queryByText('Native integrations')).not.toBeInTheDocument())+ },+}++export const SourcesDisabled: Story = {+ parameters: { featureFlags: [] },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click((await canvas.findAllByText('Add source'))[0])+ const body = within(canvasElement.ownerDocument.body)+ await body.findByText('Native integrations')+ expect(body.queryByText('Apple Ads')).not.toBeInTheDocument()+ expect(body.queryAllByText(/^new$/i)).toHaveLength(0)+ },+}diff --git a/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx b/products/marketing_analytics/frontend/components/AddIntegrationButton.tsxnew file mode 100644index 000000000000..4a97f6dc8f22--- /dev/null+++ b/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx@@ -0,0 +1,128 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconPlusSmall } from '@posthog/icons'+import { LemonButton, LemonMenu, LemonMenuItems, LemonTag } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'+import {+ VALID_NON_NATIVE_MARKETING_SOURCES,+ VALID_SELF_MANAGED_MARKETING_SOURCES,+ getEnabledNativeMarketingSources,+ nativeSourceDisplayLabel,+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'++import { newAdSourcesLogic } from './newAdSourcesLogic'++interface AddIntegrationButtonProps {+ onIntegrationSelect?: (integrationId: string) => void+}++export function AddIntegrationButton({ onIntegrationSelect }: AddIntegrationButtonProps = {}): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const { newSources, showNotice } = useValues(newAdSourcesLogic)+ const { dismissNotice } = useActions(newAdSourcesLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })+ const [showPopover, setShowPopover] = useState(false)+ const [showNoticeInMenu, setShowNoticeInMenu] = useState(false)+ const showNewSources = showNotice && !restrictedReason+ const showNewSourcesInMenu = showNoticeInMenu && newSources.length > 0 && !restrictedReason++ const handleVisibilityChange = (visible: boolean): void => {+ setShowPopover(visible)+ setShowNoticeInMenu(visible && showNewSources)+ if (visible && showNewSources) {+ dismissNotice()+ }+ }++ const handleIntegrateClick = (integrationId: string): void => {+ onIntegrationSelect?.(integrationId)+ handleVisibilityChange(false)+ }++ const groups = [+ { title: 'Native integrations', sources: getEnabledNativeMarketingSources(featureFlags) },+ { title: 'External sources', sources: VALID_NON_NATIVE_MARKETING_SOURCES },+ { title: 'Self-managed sources', sources: VALID_SELF_MANAGED_MARKETING_SOURCES },+ ]+ const items: LemonMenuItems = [+ ...(showNewSourcesInMenu+ ? [+ {+ key: 'new-ad-sources',+ title: (+ <div className="w-72 max-w-full p-2 space-y-2">+ <div className="font-semibold">New ad sources</div>+ <p className="m-0 text-muted text-sm">+ {`Connect ${newSources.map(nativeSourceDisplayLabel).join(', ')} to compare spend and conversions.`}+ </p>+ </div>+ ),+ items: [],+ },+ ]+ : []),+ ...groups+ .filter(({ sources }) => sources.length > 0)+ .map(({ title, sources }) => ({+ title,+ items: sources.map((integrationId) => ({+ key: integrationId,+ label: nativeSourceDisplayLabel(integrationId),+ icon: <SourceIcon type={integrationId} size="xsmall" disableTooltip />,+ tag:+ showNewSourcesInMenu && newSources.some((source) => source === integrationId)+ ? ('new' as const)+ : undefined,+ disabledReason: restrictedReason,+ to: onIntegrationSelect+ ? undefined+ : urls.dataWarehouseSourceNew(+ integrationId,+ urls.marketingAnalyticsApp(),+ 'Marketing analytics'+ ),+ onClick: () => handleIntegrateClick(integrationId),+ })),+ })),+ ]++ return (+ <LemonMenu+ items={items}+ visible={showPopover}+ onVisibilityChange={handleVisibilityChange}+ focusBasedKeyboardNavigation={showPopover}+ closeOnClickInside={false}+ placement="bottom-end"+ maxContentWidth+ >+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlusSmall />}+ data-attr="add-integration"+ aria-label="Add source"+ disabledReason={restrictedReason}+ tooltip={restrictedReason ? undefined : 'New ad sources are available'}+ tooltipForceMount={restrictedReason || (showNewSources && !showPopover) ? undefined : false}+ >+ <span>Add source</span>+ {showNewSources && (+ <LemonTag type="option" size="small" className="ml-2">+ New+ </LemonTag>+ )}+ </LemonButton>+ </LemonMenu>+ )+}diff --git a/products/marketing_analytics/frontend/components/newAdSourcesLogic.test.ts b/products/marketing_analytics/frontend/components/newAdSourcesLogic.test.tsnew file mode 100644index 000000000000..54c779c07962--- /dev/null+++ b/products/marketing_analytics/frontend/components/newAdSourcesLogic.test.ts@@ -0,0 +1,63 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import { NEW_AD_SOURCES_SEEN_KEY, newAdSourcesLogic } from './newAdSourcesLogic'++describe('newAdSourcesLogic', () => {+ beforeEach(() => {+ initKeaTests()+ featureFlagLogic.mount()+ userLogic.mount()+ newAdSourcesLogic.mount()+ })++ it.each([+ ['an enabled source', true, {}, true, true],+ ['disabled sources', false, {}, true, false],+ ['a non-boolean flag', 'control', {}, true, false],+ ['an existing dismissal', true, { [NEW_AD_SOURCES_SEEN_KEY]: true }, true, false],+ ['a user still loading', true, {}, false, false],+ ])('only announces available sources for %s', (_label, flag, seen, loaded, expected) => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_APPLE_ADS]: flag })+ userLogic.actions.loadUserSuccess(loaded ? { ...MOCK_DEFAULT_USER, has_seen_product_intro_for: seen } : null)+ expect(newAdSourcesLogic.values.showNotice).toBe(expected)+ expect(newAdSourcesLogic.values.newSources).toEqual(flag === true ? ['AppleSearchAds'] : [])+ })++ it('hides the shared notice immediately and remembers dismissal on remount', async () => {+ let saved = false+ useMocks({+ patch: {+ '/api/users/@me/product_intro_seen': async ({ request }) => {+ expect(await request.json()).toEqual({ product_key: NEW_AD_SOURCES_SEEN_KEY, seen: true })+ saved = true+ return [200, { [NEW_AD_SOURCES_SEEN_KEY]: true }]+ },+ },+ get: {+ '/api/users/@me/': () => [+ 200,+ { ...MOCK_DEFAULT_USER, has_seen_product_intro_for: { [NEW_AD_SOURCES_SEEN_KEY]: saved } },+ ],+ },+ })+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_APPLE_ADS]: true })+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, has_seen_product_intro_for: {} })+ const finish = expectLogic(newAdSourcesLogic, () =>+ newAdSourcesLogic.actions.dismissNotice()+ ).toFinishAllListeners()+ expect(newAdSourcesLogic.values.showNotice).toBe(false)+ await finish+ expect(saved).toBe(true)+ newAdSourcesLogic.unmount()+ newAdSourcesLogic.mount()+ expect(newAdSourcesLogic.values.showNotice).toBe(false)+ })+})diff --git a/products/marketing_analytics/frontend/components/newAdSourcesLogic.ts b/products/marketing_analytics/frontend/components/newAdSourcesLogic.tsnew file mode 100644index 000000000000..3199ce129c43--- /dev/null+++ b/products/marketing_analytics/frontend/components/newAdSourcesLogic.ts@@ -0,0 +1,110 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'++import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { userLogic } from 'scenes/userLogic'+import { getEnabledNativeMarketingSources } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import { NativeMarketingSource } from '~/queries/schema/schema-general'+import { UserType } from '~/types'++// Persisted on the user; changing this key shows the announcement again everywhere.+export const NEW_AD_SOURCES_SEEN_KEY = 'marketing-new-ad-sources-v1'++const NEW_AD_SOURCES = new Set<NativeMarketingSource>(['AppleSearchAds', 'OpenAIAds', 'AmazonAds'])++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newAdSourcesLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ user: UserType | null // userLogic+ dismissedUserId: number | null+ newSources: readonly NativeMarketingSource[]+ showNotice: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newAdSourcesLogicActions {+ updateHasSeenProductIntroFor: (+ productKey: string,+ value?: boolean | undefined+ ) => {+ productKey: string+ value: boolean+ } // userLogic+ dismissNotice: () => {+ value: true+ }+ setDismissedUserId: (userId: number) => {+ userId: number+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newAdSourcesLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ newSources: (featureFlags: FeatureFlagsSet) => readonly NativeMarketingSource[]+ showNotice: (+ user: UserType | null,+ newSources: readonly (+ | 'AmazonAds'+ | 'AppleSearchAds'+ | 'BingAds'+ | 'GoogleAds'+ | 'LinkedinAds'+ | 'MetaAds'+ | 'OpenAIAds'+ | 'PinterestAds'+ | 'RedditAds'+ | 'RoktAds'+ | 'SnapchatAds'+ | 'TikTokAds'+ )[],+ dismissedUserId: number | null+ ) => boolean+ }+}++export type newAdSourcesLogicType = MakeLogicType<+ newAdSourcesLogicValues,+ newAdSourcesLogicActions,+ Record<string, any>,+ newAdSourcesLogicMeta+>++export const newAdSourcesLogic = kea<newAdSourcesLogicType>([+ path(['products', 'marketing_analytics', 'frontend', 'components', 'newAdSourcesLogic']),+ connect({+ values: [featureFlagLogic, ['featureFlags'], userLogic, ['user']],+ actions: [userLogic, ['updateHasSeenProductIntroFor']],+ }),+ actions({ dismissNotice: true, setDismissedUserId: (userId: number) => ({ userId }) }),+ reducers({+ dismissedUserId: [null as number | null, { setDismissedUserId: (_, { userId }) => userId }],+ }),+ selectors({+ newSources: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): readonly NativeMarketingSource[] =>+ getEnabledNativeMarketingSources(featureFlags).filter((source) => NEW_AD_SOURCES.has(source)),+ ],+ showNotice: [+ (s) => [s.user, s.newSources, s.dismissedUserId],+ (+ user: UserType | null,+ newSources: readonly NativeMarketingSource[],+ dismissedUserId: number | null+ ): boolean =>+ !!user &&+ newSources.length > 0 &&+ dismissedUserId !== user.id &&+ !user.has_seen_product_intro_for?.[NEW_AD_SOURCES_SEEN_KEY],+ ],+ }),+ listeners(({ actions, values }) => ({+ dismissNotice: () => {+ if (values.user && values.showNotice) {+ actions.setDismissedUserId(values.user.id)+ actions.updateHasSeenProductIntroFor(NEW_AD_SOURCES_SEEN_KEY)+ }+ },+ })),+])diff --git a/tsconfig.json b/tsconfig.jsonindex 007b07166bd1..eeb333e01b19 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -28,6 +28,7 @@// files (products/*/frontend) can't reach by walking up from their own directory."@storybook/react": ["./frontend/node_modules/@storybook/react/dist/index.d.ts"],"storybook/preview-api": ["./frontend/node_modules/storybook/dist/preview-api/index.d.ts"],+ "storybook/test": ["./frontend/node_modules/storybook/dist/test/index.d.ts"],"react-dom/server": ["./frontend/node_modules/@types/react-dom/server.d.ts"],"@tiptap/*": ["./frontend/node_modules/@tiptap/*"],// Needed to access the subpath since torph didn't set up types properly