Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(subscriptions): create a subscription from the subscriptions page (#93040)

Rafael Audibert2c0dbb8d56a5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 00893e64bbd5..585b6594648e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5580,6 +5580,14 @@ snapshots:
hash: v1.k794b7964.e72031a3a874ed6a1825089edff6147a3ea0d74c20c74951f8b5d38d92f54464.WQmsYZby7Raw1OaQn_oKtu1eASs_te6AgRALWXM6xLE
products-signals-self-driving-intro-modal--default--light:
hash: v1.k794b7964.602b1235812b95a5a5e1b8394fcb0bf613698958302c0d8555e89c587e258c36.00YN2IU5qnM8hUXbxAhMv5wX7Hiwrxw4vYXXOWKu1Is
+ products-subscriptions-new-subscription-target--pick-what-to-send--dark:
+ hash: v1.k794b7964.256d7c2817c80a78143a68aa757935c7d5676e8a32ce6e38a705beb49de0ea2b.bT_FOHDP86GzzCJQ2oIXQBfhq6Mp1sxjharW6zoRjho
+ products-subscriptions-new-subscription-target--pick-what-to-send--light:
+ hash: v1.k794b7964.49a6e33deddd0075162c5634131eaea679512623c7536886c176079ab939559d.ghCpyCi5wnPgNXh9zDuBWvfwV83nJgplqMhtItYvQ4w
+ products-subscriptions-new-subscription-target--without-ai-prompts--dark:
+ hash: v1.k794b7964.45de098efffca42dcea68553b7a80e5efe68a017b2bff44bce74b7093e930eb7.9FhkjUGU2V7zGi7iQ8F5QfVAlhB-QMIxUvRa03HE1sE
+ products-subscriptions-new-subscription-target--without-ai-prompts--light:
+ hash: v1.k794b7964.a59d597328fc4b0b38adc693a3268e6eac7176d996a2dc6693ba994bf4fcc9c6.gLaMWqS88P5I2Q0H354DYnC7RBJAawv0qDgYOg3tVt8
products-subscriptions-subscription-delivery-history--empty--dark:
hash: v1.k794b7964.267363ce3a0453be58b96ef2c00446ae4aaf5ed42b02472c495b3c468f25e18f.PjabhWWV-dc6vzuSl_wdoaQ2VAB35IG84kOVKe5eaA4
products-subscriptions-subscription-delivery-history--empty--light:
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index 9b3f73ee1f80..3f910e0f5004 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -15,6 +15,7 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { InsightShortId, IntegrationType, SubscriptionType } from '~/types'
+import { newSubscriptionTargetLogic } from '../../scenes/newSubscriptionTargetLogic'
import { subscriptionLogic } from './subscriptionLogic'
jest.mock('posthog-js')
@@ -370,6 +371,19 @@ describe('subscriptionLogic', () => {
})
})
+ // The subscriptions scene can pick an insight to send, and reaches the same URL. Forcing
+ // the AI type there would turn every snapshot subscription started from that scene into a
+ // report from a prompt.
+ it('keeps a snapshot subscription when the parent-less URL carries an insight', async () => {
+ const insightLogic = subscriptionLogic({ insightShortId: Insight1, id: 'new' })
+ insightLogic.mount()
+
+ router.actions.push('/subscriptions/new')
+ await expectLogic(insightLogic).toFinishListeners()
+
+ expect(insightLogic.values.subscription.resource_type).toBe('insight')
+ })
+
it.each([
['an unsupported frequency', 'frequency=hourly', 'frequency', 'weekly'],
['a blank prompt', 'prompt=', 'prompt', undefined],
@@ -684,6 +698,21 @@ describe('subscriptionLogic', () => {
expect(getRecentSlackChannelIds(7)).toEqual(expectedIds)
})
+ // The scene picks a target before the form opens, and a create routes away from the scene.
+ // A target left behind skips the picker on the next visit and reuses the old insight.
+ it('clears a target picked on the subscriptions scene', async () => {
+ const targetLogic = newSubscriptionTargetLogic()
+ targetLogic.mount()
+ targetLogic.actions.chooseInsight('abc123' as InsightShortId, 'Weekly signups')
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.submitSubscriptionSuccess({ target_type: 'email' } as SubscriptionType)
+ }).toFinishListeners()
+
+ expect(targetLogic.values.target).toBeNull()
+ targetLogic.unmount()
+ })
+
it('rejects empty prompt when resource_type is ai_prompt', async () => {
// The parent-less /subscriptions/new route is the AI flow; its urlToAction sets
// resource_type='ai_prompt' (the /insights/... route forces 'insight').
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
index c1936ca43fe7..2fa53780a3ac 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
@@ -36,6 +36,7 @@ import type { OrganizationType, UserType } from '../../../../../frontend/src/typ
import type { AIPromptConfigApi } from '../../generated/api.schemas'
import type { SubscriptionAIWindowModeEnumApi } from '../../generated/api.schemas'
import type { DeliveryConfigApi } from '../../generated/api.schemas'
+import { newSubscriptionTargetLogic } from '../../scenes/newSubscriptionTargetLogic'
import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'
import { SUBSCRIPTION_PREFILL_PARAMS } from './subscriptionNudge'
import { subscriptionsLogic } from './subscriptionsLogic'
@@ -752,6 +753,10 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
if (subscription?.target_type === 'slack' && subscription.target_value && subscription.integration_id) {
recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))
}
+ // A create started from the subscriptions scene routes to the new subscription's own
+ // page, so the picker never sees the modal close. Without this the next visit to
+ // /subscriptions/new reuses the target instead of asking for one.
+ newSubscriptionTargetLogic.findMounted()?.actions.reset()
},
replaceTeamsWebhook: () => {
actions.setSubscriptionValue('target_value', '')
@@ -1033,7 +1038,14 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
actions.loadSubscription()
},
'/subscriptions/new': (_, searchParams) => {
- actions.loadSubscriptionSuccess({ ...NEW_SUBSCRIPTION, resource_type: SubscriptionResourceTypes.AiPrompt })
+ // The subscriptions scene can now pick an insight or dashboard to send, which
+ // arrives as props. Without one there is nothing to snapshot, so the only thing
+ // this route can create is a report from a prompt.
+ const isParentless = !props.insightShortId && !props.dashboardId
+ actions.loadSubscriptionSuccess({
+ ...NEW_SUBSCRIPTION,
+ ...(isParentless ? { resource_type: SubscriptionResourceTypes.AiPrompt } : {}),
+ })
if (searchParams.target_type) {
actions.setSubscriptionValue('target_type', searchParams.target_type)
}
diff --git a/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx b/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx
index e531c9ed5694..a42e52b73309 100644
--- a/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx
+++ b/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx
@@ -3,7 +3,7 @@ import { router } from 'kea-router'
import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
import { IconEllipsis } from '@posthog/icons'
-import { LemonButton, LemonMenu, LemonModal, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonMenu, LemonModal } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
@@ -26,7 +26,8 @@ import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/
import { subscriptionLogic } from '../components/Subscriptions/subscriptionLogic'
import { SubscriptionWizard } from '../components/Subscriptions/SubscriptionWizard'
import { requestSubscriptionWizardCancellation } from '../components/Subscriptions/utils'
-import { EditSubscription } from '../components/Subscriptions/views/EditSubscription'
+import { EditSubscription, SubscriptionFormSkeleton } from '../components/Subscriptions/views/EditSubscription'
+import { NewSubscriptionTarget } from './components/NewSubscriptionTarget'
import { SubscriptionsFiltersBar } from './components/SubscriptionsFiltersBar'
import {
SubscriptionsTable,
@@ -34,6 +35,7 @@ import {
subscriptionEditHref,
subscriptionName,
} from './components/SubscriptionsTable'
+import { newSubscriptionTargetLogic } from './newSubscriptionTargetLogic'
import { SubscriptionsTab, subscriptionsSceneLogic } from './subscriptionsSceneLogic'
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
@@ -122,9 +124,24 @@ export function SubscriptionsScene(): JSX.Element {
subscriptionModalId,
aiSubscriptionsAvailable,
} = useValues(subscriptionsSceneLogic)
+ const {
+ target: newSubscriptionTarget,
+ dashboard: newSubscriptionDashboard,
+ dashboardLoading: newSubscriptionDashboardLoading,
+ } = useValues(newSubscriptionTargetLogic)
+ const { reset: resetNewSubscriptionTarget } = useActions(newSubscriptionTargetLogic)
const subscriptionWizardExperimentEnabled = useFeatureFlag('SUBSCRIPTION_CREATION_WIZARD', 'test')
const isWizard = subscriptionModalId === 'new' && subscriptionWizardExperimentEnabled
- const cancelWizard = (): void => router.actions.push(urls.subscriptions())
+ const insightTarget = newSubscriptionTarget?.kind === 'insight' ? newSubscriptionTarget : null
+ const dashboardTargetPending = newSubscriptionTarget?.kind === 'dashboard' && !newSubscriptionDashboard
+ // A dashboard that failed to load leaves nothing to send, so the picker comes back.
+ const isPickingTarget =
+ subscriptionModalId === 'new' &&
+ (newSubscriptionTarget === null || (dashboardTargetPending && !newSubscriptionDashboardLoading))
+ const cancelWizard = (): void => {
+ resetNewSubscriptionTarget()
+ router.actions.push(urls.subscriptions())
+ }
const requestWizardCancel = (): void => {
const wizardForm = subscriptionLogic.findMounted({ id: 'new', creationSource: 'wizard' })
if (!wizardForm) {
@@ -157,17 +174,14 @@ export function SubscriptionsScene(): JSX.Element {
const emptyStateDescription = aiSubscriptionsAvailable
? 'Send scheduled dashboard and insight snapshots, or use an AI prompt to generate a recurring report. Deliver subscriptions to Slack or email.'
: 'Get recurring email or Slack digests, or scheduled exports from insights and dashboards. Use them for weekly rollups, stakeholder updates, or wiring metrics into your own systems.'
- const emptyStateAction = aiSubscriptionsAvailable ? (
- <span className="italic">
- <Link to={urls.subscriptionNew()}>Create an AI prompt subscription</Link>, or open a{' '}
- <Link to={urls.dashboards()}>dashboard</Link> or <Link to={urls.insights()}>saved insight</Link> to schedule
- a snapshot.
- </span>
- ) : (
- <span className="italic">
- Open a <Link to={urls.dashboards()}>dashboard</Link> or <Link to={urls.insights()}>saved insight</Link> to
- schedule a snapshot.
- </span>
+ const emptyStateAction = (
+ <LemonButton
+ type="primary"
+ data-attr="new-subscription-button-empty-state"
+ onClick={() => router.actions.push(urls.subscriptionNew())}
+ >
+ New subscription
+ </LemonButton>
)
return (
@@ -177,15 +191,13 @@ export function SubscriptionsScene(): JSX.Element {
description={sceneConfigurations[Scene.Subscriptions].description}
resourceType={{ type: 'inbox' }}
actions={
- aiSubscriptionsAvailable ? (
- <LemonButton
- type="primary"
- data-attr="new-subscription-button"
- onClick={() => router.actions.push(urls.subscriptionNew())}
- >
- New prompt subscription
- </LemonButton>
- ) : undefined
+ <LemonButton
+ type="primary"
+ data-attr="new-subscription-button"
+ onClick={() => router.actions.push(urls.subscriptionNew())}
+ >
+ New subscription
+ </LemonButton>
}
/>
<LemonTabs
@@ -227,14 +239,33 @@ export function SubscriptionsScene(): JSX.Element {
{subscriptionModalId !== null && (
<LemonModal
isOpen
- onClose={isWizard ? requestWizardCancel : cancelWizard}
- simple={isWizard}
- width={isWizard ? 720 : 650}
+ onClose={isWizard && !isPickingTarget ? requestWizardCancel : cancelWizard}
+ simple={isWizard && !isPickingTarget}
+ width={isWizard && !isPickingTarget ? 720 : 650}
+ title={isPickingTarget ? 'New subscription' : undefined}
>
- {isWizard ? (
- <SubscriptionWizard onCancel={cancelWizard} />
+ {isPickingTarget ? (
+ <NewSubscriptionTarget
+ aiSubscriptionsAvailable={aiSubscriptionsAvailable}
+ onCancel={cancelWizard}
+ />
+ ) : dashboardTargetPending ? (
+ <SubscriptionFormSkeleton />
+ ) : isWizard ? (
+ <SubscriptionWizard
+ insightShortId={insightTarget?.shortId}
+ insightName={insightTarget?.name}
+ dashboard={newSubscriptionDashboard}
+ onCancel={cancelWizard}
+ />
) : (
- <EditSubscription id={subscriptionModalId} onCancel={cancelWizard} onDelete={cancelWizard} />
+ <EditSubscription
+ id={subscriptionModalId}
+ insightShortId={insightTarget?.shortId}
+ dashboard={newSubscriptionDashboard}
+ onCancel={cancelWizard}
+ onDelete={cancelWizard}
+ />
)}
</LemonModal>
)}
diff --git a/products/subscriptions/frontend/scenes/components/NewSubscriptionTarget.stories.tsx b/products/subscriptions/frontend/scenes/components/NewSubscriptionTarget.stories.tsx
new file mode 100644
index 000000000000..b2381897e05d
--- /dev/null
+++ b/products/subscriptions/frontend/scenes/components/NewSubscriptionTarget.stories.tsx
@@ -0,0 +1,48 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { NewSubscriptionTarget } from './NewSubscriptionTarget'
+
+const INSIGHTS = [
+ { id: 11, short_id: 'ins11', name: 'Weekly active users' },
+ { id: 12, short_id: 'ins12', name: 'Signup funnel' },
+ { id: 13, short_id: 'ins13', name: '', derived_name: 'Pageviews by browser' },
+]
+
+const DASHBOARDS = [
+ { id: 1, name: 'Weekly metrics' },
+ { id: 2, name: 'Growth' },
+]
+
+const meta: Meta<typeof NewSubscriptionTarget> = {
+ title: 'Products/Subscriptions/New subscription target',
+ component: NewSubscriptionTarget,
+ parameters: { testOptions: { viewport: { width: 720, height: 420 } } },
+ decorators: [
+ (Story) => {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/insights/': { count: INSIGHTS.length, results: INSIGHTS },
+ '/api/projects/:team_id/dashboards/': { count: DASHBOARDS.length, results: DASHBOARDS },
+ },
+ })
+ return (
+ <div className="p-4 max-w-160">
+ <Story />
+ </div>
+ )
+ },
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof NewSubscriptionTarget>
+
+export const PickWhatToSend: Story = {
+ args: { aiSubscriptionsAvailable: true, onCancel: () => {} },
+}
+
+export const WithoutAiPrompts: Story = {
+ args: { aiSubscriptionsAvailable: false, onCancel: () => {} },
+}
diff --git a/products/subscriptions/frontend/scenes/components/NewSubscriptionTarget.tsx b/products/subscriptions/frontend/scenes/components/NewSubscriptionTarget.tsx
new file mode 100644
index 000000000000..8a9ccc445f30
--- /dev/null
+++ b/products/subscriptions/frontend/scenes/components/NewSubscriptionTarget.tsx
@@ -0,0 +1,108 @@
+import { useActions, useValues } from 'kea'
+
+import { IconDashboard, IconGraph, IconSparkles } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
+
+import { dashboardsModel } from '~/models/dashboardsModel'
+import { InsightShortId } from '~/types'
+
+import { newSubscriptionTargetLogic, NewSubscriptionTargetKind } from '../newSubscriptionTargetLogic'
+
+interface NewSubscriptionTargetProps {
+ aiSubscriptionsAvailable: boolean
+ onCancel: () => void
+}
+
+const KIND_LABELS: Record<NewSubscriptionTargetKind, string> = {
+ insight: 'An insight',
+ dashboard: 'A dashboard',
+ ai: 'An AI prompt',
+}
+
+/**
+ * First step of creating a subscription from the subscriptions scene. Elsewhere the
+ * subscription is created from the insight or dashboard it sends, so the form already
+ * knows what to snapshot; here the user picks that first.
+ */
+export function NewSubscriptionTarget({ aiSubscriptionsAvailable, onCancel }: NewSubscriptionTargetProps): JSX.Element {
+ const { kind, insightOptions, insightOptionsLoading } = useValues(newSubscriptionTargetLogic)
+ const { setKind, setInsightSearch, chooseInsight, chooseDashboard, chooseAiPrompt } =
+ useActions(newSubscriptionTargetLogic)
+ const { nameSortedDashboards, dashboardsLoading } = useValues(dashboardsModel)
+
+ const kinds: { key: NewSubscriptionTargetKind; icon: JSX.Element }[] = [
+ { key: 'insight', icon: <IconGraph /> },
+ { key: 'dashboard', icon: <IconDashboard /> },
+ ...(aiSubscriptionsAvailable ? [{ key: 'ai' as const, icon: <IconSparkles /> }] : []),
+ ]
+
+ return (
+ <div className="flex flex-col gap-4">
+ <LemonLabel>What should we send?</LemonLabel>
+ <div className="flex flex-wrap gap-2">
+ {kinds.map(({ key, icon }) => (
+ <LemonButton
+ key={key}
+ type={kind === key ? 'primary' : 'secondary'}
+ icon={icon}
+ data-attr={`new-subscription-target-${key}`}
+ onClick={() => (key === 'ai' ? chooseAiPrompt() : setKind(key))}
+ >
+ {KIND_LABELS[key]}
+ </LemonButton>
+ ))}
+ </div>
+
+ {kind === 'insight' && (
+ <LemonInputSelect
+ mode="single"
+ placeholder="Search your saved insights"
+ value={[]}
+ onInputChange={setInsightSearch}
+ onChange={(values) => {
+ const shortId = values[0] as InsightShortId | undefined
+ const picked = insightOptions.find((option) => option.shortId === shortId)
+ if (shortId && picked) {
+ chooseInsight(shortId, picked.name)
+ }
+ }}
+ options={insightOptions.map((option) => ({ key: option.shortId, label: option.name }))}
+ loading={insightOptionsLoading}
+ // The search runs on the server, so the list is already the answer to it.
+ disableFiltering
+ data-attr="new-subscription-insight-select"
+ />
+ )}
+
+ {kind === 'dashboard' && (
+ <LemonInputSelect
+ mode="single"
+ placeholder="Search your dashboards"
+ value={[]}
+ onChange={(values) => {
+ const id = Number(values[0])
+ const picked = nameSortedDashboards.find((dashboard) => dashboard.id === id)
+ if (picked) {
+ chooseDashboard(id, picked.name || 'Untitled')
+ }
+ }}
+ options={nameSortedDashboards.map((dashboard) => ({
+ key: String(dashboard.id),
+ label: dashboard.name || 'Untitled',
+ }))}
+ loading={dashboardsLoading}
+ data-attr="new-subscription-dashboard-select"
+ />
+ )}
+
+ <div className="flex justify-end">
+ <LemonButton type="secondary" onClick={onCancel}>
+ Cancel
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/subscriptions/frontend/scenes/newSubscriptionTargetLogic.test.ts b/products/subscriptions/frontend/scenes/newSubscriptionTargetLogic.test.ts
new file mode 100644
index 000000000000..3c02c6a02900
--- /dev/null
+++ b/products/subscriptions/frontend/scenes/newSubscriptionTargetLogic.test.ts
@@ -0,0 +1,48 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+import { DashboardType } from '~/types'
+
+import { newSubscriptionTargetLogic } from './newSubscriptionTargetLogic'
+
+describe('newSubscriptionTargetLogic', () => {
+ let logic: ReturnType<typeof newSubscriptionTargetLogic.build>
+ let dashboardSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ dashboardSpy = jest.spyOn(api.dashboards, 'get')
+ initKeaTests()
+ logic = newSubscriptionTargetLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ dashboardSpy.mockRestore()
+ logic.unmount()
+ })
+
+ // The creation form needs the dashboard's tiles to offer its insights, so a target picked
+ // without that fetch leaves the modal with nothing to render.
+ it('fetches the dashboard a target was picked from', async () => {
+ dashboardSpy.mockResolvedValue({ id: 7, name: 'Weekly review', tiles: [] } as unknown as DashboardType)
+
+ logic.actions.chooseDashboard(7, 'Weekly review')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dashboardSpy).toHaveBeenCalledWith(7)
+ expect(logic.values.target).toEqual({ kind: 'dashboard', id: 7, name: 'Weekly review' })
+ expect(logic.values.dashboard).toMatchObject({ id: 7 })
+ })
+
+ it('drops the target when the dashboard cannot be loaded', async () => {
+ dashboardSpy.mockRejectedValue(new Error('gone'))
+
+ logic.actions.chooseDashboard(7, 'Weekly review')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.target).toBeNull()
+ expect(logic.values.dashboard).toBeNull()
+ })
+})
diff --git a/products/subscriptions/frontend/scenes/newSubscriptionTargetLogic.ts b/products/subscriptions/frontend/scenes/newSubscriptionTargetLogic.ts
new file mode 100644
index 000000000000..aead927b1555
--- /dev/null
+++ b/products/subscriptions/frontend/scenes/newSubscriptionTargetLogic.ts
@@ -0,0 +1,202 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+
+import { DashboardType, InsightShortId } from '~/types'
+
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+
+import type { InsightModel } from '../../../../frontend/src/types'
+
+/** How many saved insights the picker offers before the user narrows them by search. */
+const INSIGHT_OPTIONS_LIMIT = 100
+
+export type NewSubscriptionTargetKind = 'insight' | 'dashboard' | 'ai'
+
+/**
+ * What a subscription started from the subscriptions scene will send. Everywhere else
+ * the target comes from the page the user was already on, so it needs picking here.
+ */
+export type NewSubscriptionTarget =
+ | { kind: 'insight'; shortId: InsightShortId; name: string }
+ | { kind: 'dashboard'; id: number; name: string }
+ | { kind: 'ai' }
+
+export interface NewSubscriptionInsightOption {
+ shortId: InsightShortId
+ name: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newSubscriptionTargetLogicValues {
+ dashboard: DashboardType | null
+ dashboardLoading: boolean
+ insightOptions: NewSubscriptionInsightOption[]
+ insightOptionsLoading: boolean
+ insightSearch: string
+ kind: NewSubscriptionTargetKind | null
+ target: NewSubscriptionTarget | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newSubscriptionTargetLogicActions {
+ chooseAiPrompt: () => {
+ value: true
+ }
+ chooseDashboard: (
+ id: number,
+ name: string
+ ) => {
+ id: number
+ name: string
+ }
+ chooseInsight: (
+ shortId: InsightShortId,
+ name: string
+ ) => {
+ name: string
+ shortId: InsightShortId
+ }
+ loadDashboard: (id: number) => number
+ loadDashboardFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDashboardSuccess: (
+ dashboard: DashboardType<InsightModel>,
+ payload?: number
+ ) => {
+ dashboard: DashboardType<InsightModel>
+ payload?: number
+ }
+ loadInsightOptions: (_: any) => any
+ loadInsightOptionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadInsightOptionsSuccess: (
+ insightOptions: NewSubscriptionInsightOption[],
+ payload?: any
+ ) => {
+ insightOptions: NewSubscriptionInsightOption[]
+ payload?: any
+ }
+ reset: () => {
+ value: true
+ }
+ setInsightSearch: (search: string) => {
+ search: string
+ }
+ setKind: (kind: NewSubscriptionTargetKind) => {
+ kind: NewSubscriptionTargetKind
+ }
+}
+
+export type newSubscriptionTargetLogicType = MakeLogicType<
+ newSubscriptionTargetLogicValues,
+ newSubscriptionTargetLogicActions
+>
+
+export const newSubscriptionTargetLogic = kea<newSubscriptionTargetLogicType>([
+ path(['products', 'subscriptions', 'frontend', 'scenes', 'newSubscriptionTargetLogic']),
+ actions({
+ setKind: (kind: NewSubscriptionTargetKind) => ({ kind }),
+ setInsightSearch: (search: string) => ({ search }),
+ chooseInsight: (shortId: InsightShortId, name: string) => ({ shortId, name }),
+ chooseDashboard: (id: number, name: string) => ({ id, name }),
+ chooseAiPrompt: true,
+ reset: true,
+ }),
+ loaders(({ values }) => ({
+ insightOptions: [
+ [] as NewSubscriptionInsightOption[],
+ {
+ loadInsightOptions: async (_, breakpoint): Promise<NewSubscriptionInsightOption[]> => {
+ await breakpoint(300)
+ const response = await insightsList(String(getCurrentTeamId()), {
+ saved: true,
+ basic: true,
+ limit: INSIGHT_OPTIONS_LIMIT,
+ search: values.insightSearch || undefined,
+ })
+ breakpoint()
+ return (response.results || [])
+ .filter((insight) => !!insight.short_id)
+ .map((insight) => ({
+ shortId: insight.short_id as InsightShortId,
+ name: insight.name || insight.derived_name || 'Untitled',
+ }))
+ },
+ },
+ ],
+ dashboard: [
+ null as DashboardType | null,
+ {
+ // The creation form needs the dashboard's tiles to offer its insights, which the
+ // app-wide dashboard list does not carry. `api.dashboards.get` returns the shape
+ // that form is typed on; the generated client returns its own dashboard type.
+ loadDashboard: async (id: number): Promise<DashboardType> => await api.dashboards.get(id),
+ },
+ ],
+ })),
+ reducers({
+ kind: [
+ null as NewSubscriptionTargetKind | null,
+ {
+ setKind: (_, { kind }) => kind,
+ reset: () => null,
+ },
+ ],
+ insightSearch: [
+ '',
+ {
+ setInsightSearch: (_, { search }) => search,
+ setKind: () => '',
+ reset: () => '',
+ },
+ ],
+ target: [
+ null as NewSubscriptionTarget | null,
+ {
+ chooseInsight: (_, { shortId, name }) => ({ kind: 'insight', shortId, name }),
+ chooseDashboard: (_, { id, name }) => ({ kind: 'dashboard', id, name }),
+ chooseAiPrompt: () => ({ kind: 'ai' }),
+ reset: () => null,
+ },
+ ],
+ dashboard: [
+ null as DashboardType | null,
+ {
+ reset: () => null,
+ },
+ ],
+ }),
+ listeners(({ actions }) => ({
+ setKind: ({ kind }) => {
+ if (kind === 'insight') {
+ actions.loadInsightOptions(null)
+ }
+ },
+ setInsightSearch: () => {
+ actions.loadInsightOptions(null)
+ },
+ // The creation form is rendered from the dashboard itself, so fetch it as soon as
+ // it is picked rather than making the form wait for a mount effect.
+ chooseDashboard: ({ id }) => {
+ actions.loadDashboard(id)
+ },
+ loadDashboardFailure: () => {
+ lemonToast.error('Could not load that dashboard. Pick it again, or try another one.')
+ actions.reset()
+ },
+ })),
+])