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(dashboards): nudge dashboard exporters toward a recurring subscription (#78772)

Vasco de Krijger617dcf313859
diff --git a/frontend/src/lib/components/ExportButton/exportCompletionToast.test.tsx b/frontend/src/lib/components/ExportButton/exportCompletionToast.test.tsx
new file mode 100644
index 000000000000..4796c0406b9f
--- /dev/null
+++ b/frontend/src/lib/components/ExportButton/exportCompletionToast.test.tsx
@@ -0,0 +1,282 @@
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { ToastContainer, toast } from 'react-toastify'
+
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+import { ExportedAssetType, ExporterFormat, InsightShortId } from '~/types'
+
+import {
+ ExportNudgeCandidate,
+ captureExportNudgeCheckFailed,
+ lookUpExportNudge,
+ resolveExportNudgeEligibility,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic'
+import { claimExportNudgeMessage } from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast'
+
+import { downloadExportedAsset } from './exporter'
+import { exportsLogic } from './exportsLogic'
+
+jest.mock('./exporter', () => ({
+ ...jest.requireActual('./exporter'),
+ downloadExportedAsset: jest.fn(),
+}))
+jest.mock('products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic', () => ({
+ lookUpExportNudge: jest.fn(() => ({ status: 'unknown' })),
+ resolveExportNudgeEligibility: jest.fn(async () => null),
+ captureExportNudgeCheckFailed: jest.fn(),
+ exportNudgeEventProperties: jest.fn(() => ({})),
+}))
+jest.mock('products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast', () => ({
+ claimExportNudgeMessage: jest.fn(),
+}))
+
+const NUDGE_CTA = 'Subscribe'
+const DASHBOARD_CANDIDATE: ExportNudgeCandidate = {
+ subject: { kind: 'dashboard', dashboardId: 7 },
+ name: 'Weekly',
+}
+const INSIGHT_CANDIDATE: ExportNudgeCandidate = {
+ subject: { kind: 'insight', insightShortId: '11' as InsightShortId },
+ name: null,
+}
+
+// Long enough to clear the nudge deadline and react-toastify's 100ms update delay, while staying
+// inside the 5s a success toast is left on screen for.
+const SETTLE_MS = 6000
+
+describe('export completion toast', () => {
+ let logic: ReturnType<typeof exportsLogic.build>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ // Stands in for the real offer: the headline, a CTA that retires the offer the way following
+ // it does, and the export's own action, which this message owns the layout of either way.
+ jest.mocked(claimExportNudgeMessage).mockImplementation(() => {
+ let accepted = false
+ return (headline, _toastId, action) => (
+ <span>
+ <span>{headline}</span>
+ {!accepted && <button onClick={() => (accepted = true)}>{NUDGE_CTA}</button>}
+ {action && <button onClick={() => void action.action()}>{action.label}</button>}
+ </span>
+ )
+ })
+ jest.mocked(lookUpExportNudge).mockReturnValue({ status: 'unknown' })
+ jest.useFakeTimers()
+ initKeaTests()
+ logic = exportsLogic()
+ logic.mount()
+ jest.spyOn(api.exports, 'list').mockResolvedValue({ results: [], count: 0 } as any)
+ jest.spyOn(api.exports, 'create').mockResolvedValue({
+ id: 31,
+ export_format: ExporterFormat.PNG,
+ has_content: true,
+ filename: 'dashboard.png',
+ created_at: '2026-05-11T19:00:00Z',
+ dashboard: 7,
+ })
+ })
+
+ afterEach(() => {
+ toast.dismiss()
+ cleanup()
+ logic.unmount()
+ jest.useRealTimers()
+ // jsdom ships no userActivation, which the export reads as a live gesture. Any test that
+ // pins it has to hand that default back.
+ delete (window.navigator as any).userActivation
+ })
+
+ it('leaves unrelated toasts alone when View exports is clicked', async () => {
+ // Only a video render offers the link, since it is the export that lands in the panel later.
+ jest.mocked(api.exports.create).mockResolvedValue({
+ id: 32,
+ export_format: ExporterFormat.MP4,
+ has_content: false,
+ filename: 'recording.mp4',
+ created_at: '2026-05-11T19:00:00Z',
+ })
+
+ render(<ToastContainer />)
+ act(() => {
+ toast.info('An unrelated notification', { toastId: 'unrelated' })
+ })
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.MP4 } })
+ // Settles the kickoff onto its success frame while staying inside the 5s it is left up for.
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(1000)
+ })
+ expect(screen.getByText('Export started')).toBeTruthy()
+ expect(screen.queryByText('An unrelated notification')).not.toBeNull()
+
+ const dismiss = jest.spyOn(toast, 'dismiss')
+ act(() => {
+ screen.getByText('View exports').click()
+ jest.advanceTimersByTime(1000)
+ })
+
+ // Without an id the button calls toast.dismiss(undefined), which clears every toast.
+ expect(dismiss).toHaveBeenCalled()
+ expect(dismiss.mock.calls[0][0]).not.toBeUndefined()
+ expect(screen.queryByText('An unrelated notification')).not.toBeNull()
+ })
+
+ it('completes the export toast without waiting for a nudge check that stalls', async () => {
+ jest.mocked(resolveExportNudgeEligibility).mockReturnValue(new Promise(() => {}))
+
+ render(<ToastContainer />)
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ // Deliberately shorter than the check's deadline: the file has already downloaded, so
+ // leaving its spinner up strands the user on "Preparing export…" for five more seconds.
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(500)
+ })
+
+ expect(screen.getByText('Export complete!')).toBeTruthy()
+ expect(screen.queryByText('Preparing export…')).toBeNull()
+
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(SETTLE_MS)
+ })
+
+ // A stall reports its own step, otherwise the readout cannot tell it from an exporter who
+ // was simply ineligible.
+ expect(captureExportNudgeCheckFailed).toHaveBeenCalledWith('timeout', expect.anything())
+ })
+
+ it.each([
+ ['a dashboard', { dashboard: 7 }, DASHBOARD_CANDIDATE],
+ ['an insight', { insight: 11, insightShortId: '11' as InsightShortId }, INSIGHT_CANDIDATE],
+ ])(
+ 'carries the offer from the first frame when %s export needs no check',
+ async (_label, exportData, candidate) => {
+ jest.mocked(lookUpExportNudge).mockReturnValue({ status: 'eligible', candidate })
+ let finishExport: (asset: ExportedAssetType) => void = () => {}
+ jest.mocked(api.exports.create).mockReturnValue(
+ new Promise<ExportedAssetType>((resolve) => {
+ finishExport = resolve
+ })
+ )
+
+ render(<ToastContainer />)
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, ...exportData } })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(100)
+ })
+
+ // Still exporting, and the offer is already readable rather than waiting for the export.
+ expect(screen.getByText('Preparing export…')).toBeTruthy()
+ expect(screen.getByText(NUDGE_CTA)).toBeTruthy()
+
+ finishExport({
+ id: 31,
+ export_format: ExporterFormat.PNG,
+ has_content: true,
+ filename: 'export.png',
+ created_at: '2026-05-11T19:00:00Z',
+ })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(SETTLE_MS)
+ })
+
+ // One toast, settled, still carrying the offer, rather than a second one alongside it.
+ expect(screen.queryByText('Preparing export…')).toBeNull()
+ expect(screen.getAllByText(NUDGE_CTA)).toHaveLength(1)
+ expect(document.querySelectorAll('.Toastify__toast')).toHaveLength(1)
+ expect(resolveExportNudgeEligibility).not.toHaveBeenCalled()
+ }
+ )
+
+ it('folds a late offer into the toast the export settled into', async () => {
+ jest.mocked(resolveExportNudgeEligibility).mockResolvedValue(DASHBOARD_CANDIDATE)
+
+ render(<ToastContainer />)
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(SETTLE_MS)
+ })
+
+ // The rewrite has to replace the settled frame react-toastify rendered from the success
+ // config, not sit alongside it.
+ expect(screen.getByText('Export complete!')).toBeTruthy()
+ expect(screen.getAllByText(NUDGE_CTA)).toHaveLength(1)
+ expect(document.querySelectorAll('.Toastify__toast')).toHaveLength(1)
+ })
+
+ it('never shows a failure while handing over a finished file', async () => {
+ // The file is ready; it just needs a fresh click to download. Routing that through a
+ // rejection paints the toast red with the internal reason on the way past.
+ Object.defineProperty(window.navigator, 'userActivation', { value: { isActive: false }, configurable: true })
+ jest.mocked(api.exports.create).mockResolvedValue({
+ id: 51,
+ export_format: ExporterFormat.PNG,
+ has_content: true,
+ filename: 'insight.png',
+ created_at: '2026-05-11T19:00:00Z',
+ })
+
+ render(<ToastContainer />)
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG } })
+
+ // Sampled across the settle, not just at the end: the red frame is transient.
+ const seen: string[] = []
+ for (let tick = 0; tick < 12; tick++) {
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(50)
+ })
+ seen.push(document.body.innerHTML)
+ }
+
+ expect(seen.some((html) => html.includes('Toastify__toast--error'))).toBe(false)
+ expect(seen.some((html) => html.includes('Export awaiting user download'))).toBe(false)
+ expect(screen.getByText('Export complete!')).toBeTruthy()
+ expect(screen.getByText('Download')).toBeTruthy()
+ })
+
+ it('leaves the finished download reachable when the offer is followed mid-export', async () => {
+ // A render that outlives the click's activation hands the file over on a Download button
+ // instead of downloading it outright, which is the case the CTA could strand.
+ Object.defineProperty(window.navigator, 'userActivation', {
+ value: { isActive: false },
+ configurable: true,
+ })
+ jest.mocked(lookUpExportNudge).mockReturnValue({ status: 'eligible', candidate: DASHBOARD_CANDIDATE })
+ let finishExport: (asset: ExportedAssetType) => void = () => {}
+ jest.mocked(api.exports.create).mockReturnValue(
+ new Promise<ExportedAssetType>((resolve) => {
+ finishExport = resolve
+ })
+ )
+
+ render(<ToastContainer />)
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(100)
+ })
+
+ act(() => {
+ screen.getByText(NUDGE_CTA).click()
+ })
+
+ finishExport({
+ id: 31,
+ export_format: ExporterFormat.PNG,
+ has_content: true,
+ filename: 'dashboard.png',
+ created_at: '2026-05-11T19:00:00Z',
+ dashboard: 7,
+ })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(SETTLE_MS)
+ })
+ // Dismissing on the CTA would take the button the file arrives on with it.
+ expect(screen.getByText('Export complete!')).toBeTruthy()
+ expect(screen.queryByText(NUDGE_CTA)).toBeNull()
+
+ act(() => {
+ screen.getByText('Download').click()
+ })
+ expect(downloadExportedAsset).toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/components/ExportButton/exportNudge.ts b/frontend/src/lib/components/ExportButton/exportNudge.ts
new file mode 100644
index 000000000000..21110b2acf17
--- /dev/null
+++ b/frontend/src/lib/components/ExportButton/exportNudge.ts
@@ -0,0 +1,149 @@
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { ToastButton } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { PromiseTimeoutError, withTimeout } from 'lib/utils/async'
+import { uuid } from 'lib/utils/dom'
+
+import { ExportedAssetType } from '~/types'
+
+import {
+ ExportNudgeCandidate,
+ captureExportNudgeCheckFailed,
+ exportNudgeEventProperties,
+ lookUpExportNudge,
+ resolveExportNudgeEligibility,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic'
+import {
+ ExportNudgeSubject,
+ exportNudgeSubjectFor,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeSubject'
+import {
+ ExportNudgeMessage,
+ claimExportNudgeMessage,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast'
+
+import { TriggerExportProps } from './exporter'
+
+const EXPORT_COMPLETE_MESSAGE = 'Export complete!'
+// The check normally answers long before the export lands.
+const NUDGE_RESOLUTION_TIMEOUT_MS = 5000
+
+/** An export's offer: known up front, or still resolving while the export runs. */
+export interface ExportNudge {
+ message: ExportNudgeMessage | null
+ resolving: Promise<ExportNudgeCandidate | null>
+}
+
+const NO_NUDGE: ExportNudge = { message: null, resolving: Promise.resolve(null) }
+
+/** What an export that acknowledged its kickoff hands to the toast it finishes on. */
+export interface KickoffToast {
+ toastId: string
+ nudge: ExportNudge
+}
+
+/**
+ * Both scenes load the subject's subscriptions to show the subscribe button's count, so most exports
+ * answer eligibility on the spot and put the offer in the toast's first frame. The rest start the
+ * check here and fold it in when the export settles.
+ */
+export const startExportNudge = (exportData: TriggerExportProps | ExportedAssetType): ExportNudge => {
+ const subject = exportNudgeSubjectFor(exportData)
+ if (!subject) {
+ return NO_NUDGE
+ }
+ const lookup = lookUpExportNudge(subject)
+ if (lookup.status === 'ineligible') {
+ return NO_NUDGE
+ }
+ if (lookup.status === 'eligible') {
+ return { message: claimExportNudgeMessage(lookup.candidate), resolving: Promise.resolve(null) }
+ }
+ return { message: null, resolving: resolveNudgeWhileExporting(subject) }
+}
+
+// A stalled or failed check must never hold up the export's own feedback.
+const resolveNudgeWhileExporting = async (subject: ExportNudgeSubject): Promise<ExportNudgeCandidate | null> =>
+ await withTimeout(resolveExportNudgeEligibility(subject), NUDGE_RESOLUTION_TIMEOUT_MS).catch((error) => {
+ if (error instanceof PromiseTimeoutError) {
+ // Every other failure reports its own step. Without this one, a stalled check looks the
+ // same as an exporter who was ineligible.
+ captureExportNudgeCheckFailed('timeout', exportNudgeEventProperties(subject))
+ }
+ return null
+ })
+
+// A toast waits to be clicked, rather than closing on a timer, while it carries both an unanswered
+// offer and a file the user has not taken yet.
+const holdOpenFor = (message: ExportNudgeMessage | null, action?: ToastButton): { autoClose?: false } =>
+ message && action ? { autoClose: false } : {}
+
+interface ToastFrame {
+ message: string | JSX.Element
+ /** Empty where the offer lays the action out beside its own CTA, so it is not rendered twice. */
+ button?: ToastButton
+}
+
+const toastFrame = (
+ message: ExportNudgeMessage | null,
+ headline: string,
+ toastId: number | string,
+ action?: ToastButton
+): ToastFrame => (message ? { message: message(headline, toastId, action) } : { message: headline, button: action })
+
+export const nudgeToastOptions = (
+ nudge: ExportNudge,
+ headline: string,
+ toastId: number | string,
+ action?: ToastButton
+): { message: string | JSX.Element; button?: ToastButton; autoClose?: false } => {
+ const frame = toastFrame(nudge.message, headline, toastId, action)
+ return { ...frame, ...holdOpenFor(nudge.message, action) }
+}
+
+/**
+ * Claiming happens here rather than when the check answers, because it reports an exposure: an
+ * export that never renders the offer must not spend it.
+ */
+export const foldNudgeIntoSettledToast = async (
+ nudge: ExportNudge,
+ toastId: string,
+ headline: string,
+ action?: ToastButton
+): Promise<void> => {
+ const candidate = await nudge.resolving
+ if (!candidate) {
+ return
+ }
+ if (!lemonToast.isActive(toastId)) {
+ captureExportNudgeCheckFailed('toast-gone', exportNudgeEventProperties(candidate.subject))
+ return
+ }
+ const message = claimExportNudgeMessage(candidate)
+ if (!message) {
+ return
+ }
+ lemonToast.updateToSuccess(toastId, message(headline, toastId, action), { ...holdOpenFor(message, action) })
+}
+
+/**
+ * Settles a finished export onto a toast carrying its Download button: the one it is already on if
+ * that is still up, a fresh one otherwise. Updating a dismissed toast does nothing, which would
+ * leave someone who closed the spinner with a file and nowhere to claim it from.
+ */
+export const settleWithDownload = async (
+ nudge: ExportNudge,
+ existingToastId: string | null,
+ onDownload: () => void
+): Promise<void> => {
+ const reuse = !!existingToastId && lemonToast.isActive(existingToastId)
+ const toastId = reuse && existingToastId ? existingToastId : 'export-complete-' + uuid()
+ const downloadButton = { label: 'Download', action: onDownload }
+ const { message, ...options } = nudgeToastOptions(nudge, EXPORT_COMPLETE_MESSAGE, toastId, downloadButton)
+
+ if (reuse) {
+ lemonToast.updateToSuccess(toastId, message, options)
+ } else {
+ lemonToast.success(message, { toastId, ...options })
+ }
+ await foldNudgeIntoSettledToast(nudge, toastId, EXPORT_COMPLETE_MESSAGE, downloadButton)
+}
diff --git a/frontend/src/lib/components/ExportButton/exportNudgeMessage.test.tsx b/frontend/src/lib/components/ExportButton/exportNudgeMessage.test.tsx
new file mode 100644
index 000000000000..2b0b094a10fa
--- /dev/null
+++ b/frontend/src/lib/components/ExportButton/exportNudgeMessage.test.tsx
@@ -0,0 +1,39 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { toast } from 'react-toastify'
+
+import { initKeaTests } from '~/test/init'
+
+import { ExportNudgeCandidate } from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic'
+import { claimExportNudgeMessage } from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast'
+
+jest.mock('products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic', () => ({
+ ...jest.requireActual('products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic'),
+ claimExportNudge: () => true,
+}))
+
+const CANDIDATE: ExportNudgeCandidate = { subject: { kind: 'dashboard', dashboardId: 7 }, name: 'Weekly numbers' }
+
+describe('export nudge message', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ it('closes only the toast it belongs to when the export action is taken', () => {
+ // Dismissing without an id closes every toast on screen, including another export's
+ // completion toast, which for a polled export is its only signal.
+ const dismiss = jest.spyOn(toast, 'dismiss').mockImplementation((() => {}) as any)
+ const action = jest.fn()
+ const message = claimExportNudgeMessage(CANDIDATE)
+
+ render(<>{message!('Export complete!', 'export-toast', { label: 'Download', action })}</>)
+ fireEvent.click(screen.getByText('Download'))
+
+ expect(action).toHaveBeenCalled()
+ expect(dismiss).toHaveBeenCalledWith('export-toast')
+ })
+})
diff --git a/frontend/src/lib/components/ExportButton/exporter.tsx b/frontend/src/lib/components/ExportButton/exporter.tsx
index 1ad9f19d5d22..19f3184f2a9f 100644
--- a/frontend/src/lib/components/ExportButton/exporter.tsx
+++ b/frontend/src/lib/components/ExportButton/exporter.tsx
@@ -1,6 +1,6 @@
import api from 'lib/api'
-import { ExportedAssetType } from '~/types'
+import { ExportedAssetType, InsightShortId } from '~/types'
export function downloadBlob(content: Blob, filename: string): void {
const anchor = document.createElement('a')
@@ -42,4 +42,9 @@ export function downloadExportedAsset(asset: ExportedAssetType): void {
}, 0)
}
-export type TriggerExportProps = Pick<ExportedAssetType, 'export_format' | 'dashboard' | 'insight' | 'export_context'>
+export type TriggerExportProps = Pick<
+ ExportedAssetType,
+ 'export_format' | 'dashboard' | 'insight' | 'export_context'
+> & {
+ insightShortId?: InsightShortId
+}
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
index f173d1735fcd..bc3054673604 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts
@@ -3,7 +3,18 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { initKeaTests } from '~/test/init'
-import { ExportedAssetType, ExporterFormat, SidePanelTab } from '~/types'
+import { ExportedAssetType, ExporterFormat, InsightShortId, SidePanelTab } from '~/types'
+
+import {
+ ExportNudgeCandidate,
+ captureExportNudgeCheckFailed,
+ lookUpExportNudge,
+ resolveExportNudgeEligibility,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic'
+import {
+ ExportNudgeMessage,
+ claimExportNudgeMessage,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast'
import { downloadExportedAsset } from './exporter'
import { exportsLogic, pickPollDelayMs } from './exportsLogic'
@@ -16,12 +27,32 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({
error: jest.fn(),
dismiss: jest.fn(),
promise: jest.fn((p) => p),
+ updateToSuccess: jest.fn(),
+ isActive: jest.fn(() => true),
},
}))
jest.mock('./exporter', () => ({
...jest.requireActual('./exporter'),
downloadExportedAsset: jest.fn(),
}))
+// The eligibility rules themselves are covered by exportNudgeLogic's tests.
+jest.mock('products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic', () => ({
+ lookUpExportNudge: jest.fn(() => ({ status: 'unknown' })),
+ resolveExportNudgeEligibility: jest.fn(async () => null),
+ captureExportNudgeCheckFailed: jest.fn(),
+ exportNudgeEventProperties: jest.fn(() => ({})),
+}))
+jest.mock('products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast', () => ({
+ claimExportNudgeMessage: jest.fn(() => null),
+}))
+
+// The nudge body stands in as an opaque element that echoes the headline it was rendered under,
+// which is what distinguishes the toast's states.
+const NUDGE_MESSAGE: ExportNudgeMessage = (headline, _toastId, action) =>
+ `nudge:${headline}${action ? ` +${action.label}` : ''}`
+
+const DASHBOARD_SUBJECT = { kind: 'dashboard' as const, dashboardId: 7 }
+const INSIGHT_SHORT_ID = '11' as InsightShortId
const asset = (overrides: Partial<ExportedAssetType> = {}): ExportedAssetType => ({
id: 1,
@@ -98,6 +129,10 @@ describe('exportsLogic', () => {
beforeEach(() => {
jest.clearAllMocks()
+ jest.mocked(lookUpExportNudge).mockReturnValue({ status: 'unknown' })
+ jest.mocked(resolveExportNudgeEligibility).mockResolvedValue(null)
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(null)
+ jest.mocked(lemonToast.isActive).mockReturnValue(true)
initKeaTests()
logic = exportsLogic()
logic.mount()
@@ -111,6 +146,12 @@ describe('exportsLogic', () => {
// Let the fire-and-forget IIFE in the createExport loader run to settlement.
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
+ // A macrotask sentinel always loses to an already-settled promise, so a regression that
+ // leaves the export toast pending reports UNSETTLED instead of timing the test out.
+ const UNSETTLED = 'unsettled'
+ const settledValueOf = async (promise: Promise<any>): Promise<any> =>
+ await Promise.race([promise, new Promise((resolve) => setTimeout(() => resolve(UNSETTLED), 0))])
+
const createCases: {
label: string
response?: ExportedAssetType
@@ -118,8 +159,8 @@ describe('exportsLogic', () => {
format: ExporterFormat
settles: { resolved: string } | { rejected: string }
expectsDownload: boolean
- freshIds: number[]
expectsViewExportsButton: boolean
+ freshIds: number[]
expectsPanelOpen: boolean
}[] = [
{
@@ -128,8 +169,8 @@ describe('exportsLogic', () => {
format: ExporterFormat.MP4,
settles: { resolved: 'Export started' },
expectsDownload: false,
- freshIds: [11],
expectsViewExportsButton: true,
+ freshIds: [11],
expectsPanelOpen: true,
},
{
@@ -138,8 +179,8 @@ describe('exportsLogic', () => {
format: ExporterFormat.CSV,
settles: { resolved: 'Export complete!' },
expectsDownload: true,
- freshIds: [],
expectsViewExportsButton: false,
+ freshIds: [],
expectsPanelOpen: false,
},
{
@@ -148,8 +189,8 @@ describe('exportsLogic', () => {
format: ExporterFormat.MP4,
settles: { rejected: 'Export failed: boom' },
expectsDownload: false,
- freshIds: [],
expectsViewExportsButton: true,
+ freshIds: [],
expectsPanelOpen: false,
},
{
@@ -158,8 +199,8 @@ describe('exportsLogic', () => {
format: ExporterFormat.MP4,
settles: { rejected: 'Export failed: network down' },
expectsDownload: false,
- freshIds: [],
expectsViewExportsButton: true,
+ freshIds: [],
expectsPanelOpen: false,
},
]
@@ -172,8 +213,8 @@ describe('exportsLogic', () => {
format,
settles,
expectsDownload,
- freshIds,
expectsViewExportsButton,
+ freshIds,
expectsPanelOpen,
}) => {
const createSpy = jest.spyOn(api.exports, 'create')
@@ -192,7 +233,9 @@ describe('exportsLogic', () => {
expect.objectContaining({ pending: 'Preparing export…' }),
expect.objectContaining({ toastId: expect.any(String) })
)
- // Video renders finish out of band, so their kickoff toast must link to the exports panel.
+ // The button rides every frame the toast has, including the pending one, where a
+ // synchronous export's row does not exist client-side yet. Only a video render,
+ // which lands in the panel minutes later, earns the link.
const toastOptions = jest.mocked(lemonToast.promise).mock.calls[0][2]
expect(toastOptions?.button?.label).toEqual(expectsViewExportsButton ? 'View exports' : undefined)
const runPromise = jest.mocked(lemonToast.promise).mock.calls[0][0]
@@ -202,6 +245,9 @@ describe('exportsLogic', () => {
await expect(runPromise).rejects.toThrow(settles.rejected)
}
expect(jest.mocked(downloadExportedAsset).mock.calls).toEqual(expectsDownload ? [[response]] : [])
+ // Only a nudge earns a toast that sits there until answered; everything else keeps
+ // the settled toast react-toastify raised, which closes on its own.
+ expect(lemonToast.updateToSuccess).not.toHaveBeenCalled()
expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual(freshIds)
// selectedTab is persisted across kea contexts, so assert the open+tab combination.
expect(
@@ -211,6 +257,240 @@ describe('exportsLogic', () => {
}
)
+ it.each([
+ ['a dashboard export', { dashboard: 7 }, [[{ kind: 'dashboard', dashboardId: 7 }]]],
+ [
+ 'an insight export',
+ { insight: 11, insightShortId: INSIGHT_SHORT_ID },
+ [[{ kind: 'insight', insightShortId: INSIGHT_SHORT_ID }]],
+ ],
+ // A CSV of a data table, a recording render, a cohort: nothing to subscribe to.
+ ['an export of anything else', {}, []],
+ ])('resolves the subscribe nudge for %s', async (_label, exportSubject, expectedCalls) => {
+ jest.spyOn(api.exports, 'create').mockResolvedValue(
+ asset({ id: 17, export_format: ExporterFormat.PNG, has_content: true })
+ )
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, ...exportSubject } })
+ await flush()
+
+ expect(jest.mocked(resolveExportNudgeEligibility).mock.calls).toEqual(expectedCalls)
+ })
+
+ it.each([ExporterFormat.CSV, ExporterFormat.XLSX])('leaves a %s export of an insight alone', async (format) => {
+ // A subscription delivers a rendered image, so offering one to someone taking rows
+ // would promise something other than what they just did.
+ jest.spyOn(api.exports, 'create').mockResolvedValue(
+ asset({ id: 19, export_format: format, has_content: true })
+ )
+
+ logic.actions.createExport({
+ exportData: { export_format: format, insightShortId: INSIGHT_SHORT_ID },
+ })
+ await flush()
+
+ expect(resolveExportNudgeEligibility).not.toHaveBeenCalled()
+ expect(lookUpExportNudge).not.toHaveBeenCalled()
+ })
+
+ it('folds an eligible nudge into the toast a polled dashboard export completes with', async () => {
+ jest.mocked(resolveExportNudgeEligibility).mockResolvedValue({
+ subject: { kind: 'dashboard', dashboardId: 8 },
+ name: null,
+ })
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(NUDGE_MESSAGE)
+ const pending = asset({ id: 18, export_format: ExporterFormat.PNG, dashboard: 8 })
+ const finished = asset({ id: 18, export_format: ExporterFormat.PNG, has_content: true, dashboard: 8 })
+
+ logic.actions.addFresh(pending)
+ logic.actions.loadExportsSuccess([finished])
+ await flush()
+
+ expect(jest.mocked(resolveExportNudgeEligibility).mock.calls).toEqual([
+ [{ kind: 'dashboard', dashboardId: 8 }],
+ ])
+ // The completion toast and its Download button are raised before the check runs, so a
+ // slow check cannot delay the only signal a polled export gives.
+ expect(lemonToast.success).toHaveBeenCalledWith(
+ 'Export complete!',
+ expect.objectContaining({ button: expect.objectContaining({ label: 'Download' }) })
+ )
+ // The nudge then folds into that same toast, and the Download hand-off stays in the
+ // standard button slot. An undelivered file plus an unanswered offer holds it open.
+ const toastId = jest.mocked(lemonToast.success).mock.calls.at(-1)![1]!.toastId
+ expect(lemonToast.updateToSuccess).toHaveBeenCalledWith(toastId, 'nudge:Export complete! +Download', {
+ autoClose: false,
+ })
+ })
+
+ it('builds the toast with the offer already in it when eligibility needs no request', async () => {
+ // The scene has already loaded what the check needs, so the offer is in the first frame
+ // the user sees and the toast is never rewritten to add it.
+ jest.mocked(lookUpExportNudge).mockReturnValue({
+ status: 'eligible',
+ candidate: { subject: DASHBOARD_SUBJECT, name: 'Weekly numbers' },
+ })
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(NUDGE_MESSAGE)
+ jest.spyOn(api.exports, 'create').mockResolvedValue(
+ asset({ id: 26, export_format: ExporterFormat.PNG, has_content: true, dashboard: 7 })
+ )
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ await flush()
+
+ const messages = jest.mocked(lemonToast.promise).mock.calls[0][1]
+ expect(messages.pending).toBe('nudge:Preparing export…')
+ // Evaluated when the toast settles, so an offer followed while the export ran is gone by
+ // then rather than being asked a second time.
+ expect(typeof messages.success).toBe('function')
+ expect((messages.success as (data?: string) => string)('Export complete!')).toBe('nudge:Export complete!')
+ expect(resolveExportNudgeEligibility).not.toHaveBeenCalled()
+ expect(lemonToast.updateToSuccess).not.toHaveBeenCalled()
+ expect(claimExportNudgeMessage).toHaveBeenCalledTimes(1)
+ })
+
+ it('settles the export toast before the nudge check answers', async () => {
+ // The file is already on disk once the create call returns, so a check that takes its
+ // full timeout must not leave the exporter watching a spinner. Both variants pay this,
+ // since eligibility is resolved before the experiment flag is ever read.
+ let resolveEligibility: (candidate: ExportNudgeCandidate | null) => void = () => {}
+ jest.mocked(resolveExportNudgeEligibility).mockReturnValue(
+ new Promise((resolve) => {
+ resolveEligibility = resolve
+ })
+ )
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(NUDGE_MESSAGE)
+ jest.spyOn(api.exports, 'create').mockResolvedValue(
+ asset({ id: 27, export_format: ExporterFormat.PNG, has_content: true, dashboard: 7 })
+ )
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ await flush()
+
+ const runPromise = jest.mocked(lemonToast.promise).mock.calls[0][0]
+ expect(await settledValueOf(runPromise)).toBe('Export complete!')
+ expect(jest.mocked(downloadExportedAsset)).toHaveBeenCalled()
+ expect(claimExportNudgeMessage).not.toHaveBeenCalled()
+
+ // The nudge then folds into that same toast rather than raising a second one, and is
+ // claimed once.
+ resolveEligibility({ subject: DASHBOARD_SUBJECT, name: null })
+ await flush()
+
+ expect(claimExportNudgeMessage).toHaveBeenCalledTimes(1)
+ expect(lemonToast.info).not.toHaveBeenCalled()
+ // The file downloaded itself, so nothing is owed and the offer alone does not hold the
+ // toast open.
+ expect(lemonToast.updateToSuccess).toHaveBeenCalledWith(
+ jest.mocked(lemonToast.promise).mock.calls[0][2]?.toastId,
+ 'nudge:Export complete!',
+ {}
+ )
+ })
+
+ it('carries one toast from kickoff through to polled completion', async () => {
+ // An async render acknowledges the kickoff, then lands minutes later. Both toasts are
+ // about the same export, so the first must go when the second arrives.
+ const rendering = asset({ id: 41, export_format: ExporterFormat.PNG, dashboard: 7 })
+ jest.spyOn(api.exports, 'create').mockResolvedValue(rendering)
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ await flush()
+ const kickoffToastId = jest.mocked(lemonToast.promise).mock.calls[0][2]?.toastId
+
+ logic.actions.loadExportsSuccess([{ ...rendering, has_content: true }])
+ await flush()
+
+ // Settled in place, so the acknowledgement does not close and animate a second toast in.
+ expect(lemonToast.updateToSuccess).toHaveBeenCalledWith(
+ kickoffToastId,
+ 'Export complete!',
+ expect.objectContaining({ button: expect.objectContaining({ label: 'Download' }) })
+ )
+ expect(lemonToast.success).not.toHaveBeenCalled()
+ expect(lemonToast.dismiss).not.toHaveBeenCalled()
+ })
+
+ it('raises a fresh toast when the kickoff toast is long gone', async () => {
+ // A render that takes minutes outlives its acknowledgement, and updating a dismissed id
+ // does nothing, so the completion has to raise a toast of its own.
+ jest.mocked(lemonToast.isActive).mockReturnValue(false)
+ const rendering = asset({ id: 43, export_format: ExporterFormat.MP4 })
+ jest.spyOn(api.exports, 'create').mockResolvedValue(rendering)
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.MP4 } })
+ await flush()
+ logic.actions.loadExportsSuccess([{ ...rendering, has_content: true }])
+ await flush()
+
+ expect(jest.mocked(lemonToast.success).mock.calls).toHaveLength(1)
+ expect(jest.mocked(lemonToast.success).mock.calls[0][1]?.toastId).toEqual(
+ expect.stringContaining('export-complete-')
+ )
+ })
+
+ it('claims the offer once across the kickoff and completion toasts', async () => {
+ // Claiming twice reports two exposures for one export and asks the same person twice.
+ jest.mocked(lookUpExportNudge).mockReturnValue({
+ status: 'eligible',
+ candidate: { subject: DASHBOARD_SUBJECT, name: 'Weekly numbers' },
+ })
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(NUDGE_MESSAGE)
+ const rendering = asset({ id: 42, export_format: ExporterFormat.PNG, dashboard: 7 })
+ jest.spyOn(api.exports, 'create').mockResolvedValue(rendering)
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 7 } })
+ await flush()
+ logic.actions.loadExportsSuccess([{ ...rendering, has_content: true }])
+ await flush()
+
+ expect(claimExportNudgeMessage).toHaveBeenCalledTimes(1)
+ // The offer follows the export to the toast it finishes on, for anyone who did not
+ // answer it while the render was running.
+ expect(jest.mocked(lemonToast.updateToSuccess).mock.calls.at(-1)![1]).toEqual(
+ 'nudge:Export complete! +Download'
+ )
+ })
+
+ it('does not claim the nudge for an export that failed', async () => {
+ jest.mocked(resolveExportNudgeEligibility).mockResolvedValue({
+ subject: { kind: 'dashboard', dashboardId: 9 },
+ name: null,
+ })
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(NUDGE_MESSAGE)
+ jest.spyOn(api.exports, 'create').mockRejectedValue(new Error('network down'))
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.PNG, dashboard: 9 } })
+ await flush()
+
+ // Nothing to subscribe to yet, and claiming would spend the dashboard's one nudge.
+ expect(claimExportNudgeMessage).not.toHaveBeenCalled()
+ expect(lemonToast.updateToSuccess).not.toHaveBeenCalled()
+ })
+
+ it('does not claim the nudge when the completion toast is already gone', async () => {
+ // Download is the expected action on that toast and dismisses it, so by the time a slow
+ // check answers there may be nothing left to render into. Claiming anyway would report
+ // an exposure and burn the dashboard's one nudge on a toast nobody saw.
+ jest.mocked(lemonToast.isActive).mockReturnValue(false)
+ jest.mocked(resolveExportNudgeEligibility).mockResolvedValue({
+ subject: { kind: 'dashboard', dashboardId: 8 },
+ name: null,
+ })
+ jest.mocked(claimExportNudgeMessage).mockReturnValue(NUDGE_MESSAGE)
+
+ logic.actions.addFresh(asset({ id: 28, export_format: ExporterFormat.PNG, dashboard: 8 }))
+ logic.actions.loadExportsSuccess([
+ asset({ id: 28, export_format: ExporterFormat.PNG, has_content: true, dashboard: 8 }),
+ ])
+ await flush()
+
+ expect(claimExportNudgeMessage).not.toHaveBeenCalled()
+ expect(lemonToast.updateToSuccess).not.toHaveBeenCalled()
+ // Without this the readout cannot tell a dropped offer from an ineligible exporter.
+ expect(captureExportNudgeCheckFailed).toHaveBeenCalledWith('toast-gone', expect.anything())
+ })
+
it('offers a Download button when the create call outlived the user gesture', async () => {
// A slow synchronous render outlives Safari's user-activation window, so an auto-download
// would be silently dropped. The export must instead surface a Download button (a fresh
@@ -227,11 +507,16 @@ describe('exportsLogic', () => {
expect(jest.mocked(downloadExportedAsset)).not.toHaveBeenCalled()
expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual([15])
- expect(lemonToast.success).toHaveBeenCalledWith(
+ // A ready file is a success, so the toast settles on one and only gains the button
+ // the file is claimed from. It is never dismissed, and never shows a failure.
+ expect(lemonToast.dismiss).not.toHaveBeenCalled()
+ expect(lemonToast.success).not.toHaveBeenCalled()
+ expect(lemonToast.updateToSuccess).toHaveBeenCalledWith(
+ expect.any(String),
'Export complete!',
expect.objectContaining({ button: expect.objectContaining({ label: 'Download' }) })
)
- jest.mocked(lemonToast.success).mock.calls.at(-1)![1]!.button!.action()
+ jest.mocked(lemonToast.updateToSuccess).mock.calls.at(-1)![2]!.button!.action()
expect(downloadExportSpy).toHaveBeenCalledWith(response)
} finally {
if (original) {
@@ -242,6 +527,57 @@ describe('exportsLogic', () => {
}
})
+ it('hands a delayed download over even when the spinner was dismissed', async () => {
+ // A pending promise toast never auto-closes, so the only way it is gone is the user
+ // closing it. Updating a dismissed id does nothing, which would lose the file.
+ const original = Object.getOwnPropertyDescriptor(navigator, 'userActivation')
+ Object.defineProperty(navigator, 'userActivation', { value: { isActive: false }, configurable: true })
+ jest.mocked(lemonToast.isActive).mockReturnValue(false)
+ try {
+ const response = asset({ id: 61, export_format: ExporterFormat.CSV, has_content: true })
+ jest.spyOn(api.exports, 'create').mockResolvedValue(response)
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.CSV } })
+ await flush()
+
+ expect(jest.mocked(lemonToast.success).mock.calls).toHaveLength(1)
+ expect(jest.mocked(lemonToast.success).mock.calls[0][1]?.button?.label).toEqual('Download')
+ } finally {
+ if (original) {
+ Object.defineProperty(navigator, 'userActivation', original)
+ } else {
+ delete (navigator as any).userActivation
+ }
+ }
+ })
+
+ it('does not announce a delayed download twice when the list is polled again', async () => {
+ // The asset waits in freshUndownloadedExports until it is clicked, so any later poll
+ // sees it complete. Announcing it again would raise a second toast and, for an eligible
+ // export, report a second exposure for one export.
+ const original = Object.getOwnPropertyDescriptor(navigator, 'userActivation')
+ Object.defineProperty(navigator, 'userActivation', { value: { isActive: false }, configurable: true })
+ try {
+ const response = asset({ id: 62, export_format: ExporterFormat.CSV, has_content: true })
+ jest.spyOn(api.exports, 'create').mockResolvedValue(response)
+
+ logic.actions.createExport({ exportData: { export_format: ExporterFormat.CSV } })
+ await flush()
+ const toastsAfterExport = jest.mocked(lemonToast.success).mock.calls.length
+
+ logic.actions.loadExportsSuccess([response])
+ await flush()
+
+ expect(jest.mocked(lemonToast.success).mock.calls).toHaveLength(toastsAfterExport)
+ } finally {
+ if (original) {
+ Object.defineProperty(navigator, 'userActivation', original)
+ } else {
+ delete (navigator as any).userActivation
+ }
+ }
+ })
+
it('notifies once with a Download button that routes through downloadExport', async () => {
const pending = asset({ id: 21, export_format: ExporterFormat.MP4, has_content: false })
const finished = asset({ id: 21, export_format: ExporterFormat.MP4, has_content: true })
@@ -262,6 +598,8 @@ describe('exportsLogic', () => {
expect.objectContaining({ button: expect.objectContaining({ label: 'Download' }) }),
],
])
+ // An insight export has nothing to subscribe to, so it never asks for a nudge.
+ expect(resolveExportNudgeEligibility).not.toHaveBeenCalled()
// The export keeps its "not downloaded" highlight until the user actually downloads it.
expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual([21])
diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.ts b/frontend/src/lib/components/ExportButton/exportsLogic.ts
index d2f461983c30..ea10da93bb50 100644
--- a/frontend/src/lib/components/ExportButton/exportsLogic.ts
+++ b/frontend/src/lib/components/ExportButton/exportsLogic.ts
@@ -1,11 +1,21 @@
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import api from 'lib/api'
import { TriggerExportProps, downloadBlob, downloadExportedAsset } from 'lib/components/ExportButton/exporter'
+import {
+ ExportNudge,
+ KickoffToast,
+ foldNudgeIntoSettledToast,
+ nudgeToastOptions,
+ settleWithDownload,
+ startExportNudge,
+} from 'lib/components/ExportButton/exportNudge'
import { isLongRunningExportFormat } from 'lib/components/ExportButton/exportStatus'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { ToastButton } from 'lib/lemon-ui/LemonToast/LemonToast'
import { delay } from 'lib/utils/async'
import { uuid } from 'lib/utils/dom'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
@@ -30,6 +40,8 @@ const POLL_DELAY_MS = 10000
// so polling every 10s produces unhelpful timeout noise. Back off when the
// pending queue is dominated by long-running formats.
const LONG_RUNNING_POLL_DELAY_MS = 30000
+const EXPORT_PENDING_MESSAGE = 'Preparing export…'
+const EXPORT_COMPLETE_MESSAGE = 'Export complete!'
// An export is still rendering while it has neither produced content nor failed.
const isRendering = (asset: ExportedAssetType): boolean => !asset.has_content && !asset.exception
@@ -57,20 +69,21 @@ export const pickPollDelayMs = (pendingAssets: ExportedAssetType[]): number => {
const isLocalExport = (context: ExportContext | undefined): context is LocalExportContext =>
!!(context && 'localData' in context)
-// Thrown when a synchronous export finished but the create request outlived the click's user
-// activation, so the download must wait for a fresh gesture (a Download button) rather than
-// auto-download — Safari silently drops programmatic downloads once activation has expired.
-class ExportAwaitingDownload extends Error {
- constructor(public readonly asset: ExportedAssetType) {
- super('Export awaiting user download')
- }
-}
-
// The user gesture that started the export is still live, so an auto-download will fire. Falls back
// to true where navigator.userActivation is unavailable (older Firefox), which tolerates a delayed
// click anyway.
const isUserActivationLive = (): boolean => navigator.userActivation?.isActive ?? true
+// For a polled export this toast is the only completion signal there is. An export that
+// acknowledged its kickoff carries its offer over rather than claiming a second one.
+const showExportCompleteToast = async (
+ asset: ExportedAssetType,
+ onDownload: () => void,
+ kickoff?: KickoffToast
+): Promise<void> => {
+ await settleWithDownload(kickoff?.nudge ?? startExportNudge(asset), kickoff?.toastId ?? null, onDownload)
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface exportsLogicValues {
assetFormat: ExporterFormat | null
@@ -274,7 +287,7 @@ export const exportsLogic = kea<exportsLogicType>([
type: exportData.export_context.mediaType,
})
downloadBlob(blob, exportData.export_context.filename)
- lemonToast.success('Export complete!')
+ lemonToast.success(EXPORT_COMPLETE_MESSAGE)
} catch (e: any) {
lemonToast.error(`Export failed with error: ${e.message}`)
}
@@ -294,6 +307,7 @@ export const exportsLogic = kea<exportsLogicType>([
},
removeFresh: ({ exportedAsset }) => {
cache.exportStatusFetchers?.delete(exportedAsset.id)
+ cache.exportKickoffToasts?.delete(exportedAsset.id)
},
createExportSuccess: () => {
actions.loadExports()
@@ -307,11 +321,18 @@ export const exportsLogic = kea<exportsLogicType>([
lemonToast.success('Download started')
},
loadExportsSuccess: async ({ exports: exportsList }, breakpoint) => {
- // Surface async exports we kicked off that have now finished: the render completes long
- // after the kickoff toast, so this poll is the only completion signal the user gets.
+ // An async render finishes long after its kickoff toast, so this poll is the only
+ // completion signal the user gets.
cache.notifiedExportIds ??= new Set<number>()
const pending = exportsList.filter(isRendering)
for (const fresh of values.freshUndownloadedExports) {
+ if (cache.notifiedExportIds.has(fresh.id)) {
+ continue
+ }
+ // Claimed before the fetch, not after. This listener runs on the poll and on a
+ // finished create call, and two runs could both pass a check placed after the await
+ // and each raise a completion toast for the same export.
+ cache.notifiedExportIds.add(fresh.id)
// The list can be format-filtered (assetFormat), so fetch directly if it's not in it.
const listed = exportsList.find((asset) => asset.id === fresh.id)
const customFetcher = cache.exportStatusFetchers?.get(fresh.id) as ExportStatusFetcher | undefined
@@ -319,22 +340,22 @@ export const exportsLogic = kea<exportsLogicType>([
? await customFetcher().catch(() => null)
: (listed ?? (await fetchExportOrNull(fresh.id)))
if (!latest || isRendering(latest)) {
- // Still rendering, or a transient fetch miss: keep an out-of-list export polling.
+ // Still rendering, or a fetch miss. Release the claim so a later poll can
+ // notify, and keep an out-of-list export polling.
+ cache.notifiedExportIds.delete(fresh.id)
if (!listed) {
pending.push(latest ?? fresh)
}
continue
}
- if (cache.notifiedExportIds.has(fresh.id)) {
- continue
- }
if (latest.has_content) {
cache.exportStatusFetchers?.delete(fresh.id)
- cache.notifiedExportIds.add(fresh.id)
const finished = latest
- lemonToast.success('Export complete!', {
- button: { label: 'Download', action: () => actions.downloadExport(finished) },
- })
+ const kickoff = cache.exportKickoffToasts?.get(fresh.id)
+ cache.exportKickoffToasts?.delete(fresh.id)
+ void showExportCompleteToast(finished, () => actions.downloadExport(finished), kickoff).catch(
+ (error) => posthog.captureException(error)
+ )
} else {
actions.removeFresh(fresh)
lemonToast.error('Export failed: ' + latest.exception)
@@ -405,7 +426,7 @@ export const exportsLogic = kea<exportsLogicType>([
},
})),
- loaders(({ values, actions }) => ({
+ loaders(({ values, actions, cache }) => ({
exports: [
[] as ExportedAssetType[],
{
@@ -430,10 +451,30 @@ export const exportsLogic = kea<exportsLogicType>([
[] as ExportedAssetType[],
{
createExport: ({ exportData }) => {
- // Non-video exports (CSV/XLSX/PNG) run synchronously on the backend, so this
- // request can block for a while. lemonToast.promise shows a spinner immediately
- // and swaps to the success/failure message when it settles, so the user always
- // gets feedback instead of a menu that looks like it did nothing.
+ const exportToastId = 'export-' + uuid()
+ // A video render lands in the exports panel minutes later, so its kickoff toast
+ // links there. A synchronous export has no row to link to while it runs.
+ const viewExportsButton: ToastButton | undefined = isLongRunningExportFormat(
+ exportData.export_format
+ )
+ ? { label: 'View exports', action: () => actions.openSidePanel(SidePanelTab.Exports) }
+ : undefined
+ const nudge: ExportNudge = startExportNudge(exportData)
+ const kickoffFrame = nudgeToastOptions(
+ nudge,
+ EXPORT_PENDING_MESSAGE,
+ exportToastId,
+ viewExportsButton
+ )
+ // Set when the export finished but the request outlived the click's user
+ // activation, so the file waits behind a Download button. Safari drops a
+ // programmatic download once activation expires. Held on an object because
+ // runExport assigns it, and the checker does not see that from this scope.
+ const awaiting: { download: ExportedAssetType | null } = { download: null }
+
+ // Non-video exports run synchronously on the backend, so this request can block
+ // for a while. lemonToast.promise shows a spinner right away and swaps to the
+ // result, so the menu never looks like it did nothing.
const runExport = async (): Promise<string> => {
let response: ExportedAssetType
try {
@@ -466,10 +507,19 @@ export const exportsLogic = kea<exportsLogicType>([
// Download button whose click is a fresh gesture.
if (isUserActivationLive()) {
downloadExportedAsset(response)
- return 'Export complete!'
+ return EXPORT_COMPLETE_MESSAGE
}
+ // Claimed before addFresh, because that is the moment the poll can see
+ // this asset. A poll running before the toast settles would otherwise
+ // announce the same export again.
+ cache.notifiedExportIds ??= new Set<number>()
+ cache.notifiedExportIds.add(response.id)
actions.addFresh(response)
- throw new ExportAwaitingDownload(response)
+ // Not a failure, so not a rejection: the export succeeded and the file
+ // is ready, it just needs a fresh click. Rejecting here would settle the
+ // toast into its error frame on the way past.
+ awaiting.download = response
+ return EXPORT_COMPLETE_MESSAGE
}
if (response.exception) {
throw new Error('Export failed: ' + response.exception)
@@ -478,47 +528,44 @@ export const exportsLogic = kea<exportsLogicType>([
// kickoff and open the exports panel, where it lands once the render finishes.
actions.addFresh(response)
actions.openSidePanel(SidePanelTab.Exports)
+ cache.exportKickoffToasts ??= new Map<number, KickoffToast>()
+ cache.exportKickoffToasts.set(response.id, { toastId: exportToastId, nudge })
return 'Export started'
}
- const exportToastId = 'export-' + uuid()
void (async () => {
try {
- await lemonToast.promise(
+ // The success frame is read when the toast settles, so an offer followed
+ // while the export was running is already gone by then, rather than
+ // being asked a second time.
+ const settledMessage: string = await lemonToast.promise(
runExport(),
{
- pending: 'Preparing export…',
- success: 'Export complete!',
+ pending: kickoffFrame.message,
+ success: (data) =>
+ nudgeToastOptions(
+ nudge,
+ data || EXPORT_COMPLETE_MESSAGE,
+ exportToastId,
+ viewExportsButton
+ ).message,
error: 'Export failed',
},
- {
- toastId: exportToastId,
- // Video renders finish minutes later in the exports panel, so the
- // kickoff toast must point somewhere instead of dead-ending.
- ...(isLongRunningExportFormat(exportData.export_format)
- ? {
- button: {
- label: 'View exports',
- action: () => actions.openSidePanel(SidePanelTab.Exports),
- },
- }
- : {}),
- }
+ { toastId: exportToastId, button: kickoffFrame.button }
)
- } catch (error) {
- if (error instanceof ExportAwaitingDownload) {
- // Content is ready but the auto-download would have been dropped —
- // replace the spinner with a Download button the user can click.
- lemonToast.dismiss(exportToastId)
- lemonToast.success('Export complete!', {
- button: {
- label: 'Download',
- action: () => actions.downloadExport(error.asset),
- },
- })
+ const readyForDownload = awaiting.download
+ if (readyForDownload) {
+ await settleWithDownload(nudge, exportToastId, () =>
+ actions.downloadExport(readyForDownload)
+ )
return
}
+ await foldNudgeIntoSettledToast(nudge, exportToastId, settledMessage, viewExportsButton)
+ } catch (error) {
const apiError = error as { data?: APIErrorType }
+ if (apiError?.data?.attr !== 'export_limit_exceeded') {
+ posthog.captureException(error)
+ }
// Show a survey when the user reaches the export limit, replacing the
// generic failure toast with the upsell.
if (apiError?.data?.attr === 'export_limit_exceeded') {
diff --git a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx
index 2e03770c91ec..8572f5845f4c 100644
--- a/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx
+++ b/frontend/src/lib/components/Scenes/InsightOrDashboard/SceneExportDropdownMenu.tsx
@@ -41,6 +41,7 @@ interface SceneExportDropdownMenuProps extends SubscriptionBaseProps {
export function SceneExportDropdownMenu({
dropdownMenuItems,
disabledReasons,
+ insightShortId,
}: SceneExportDropdownMenuProps): JSX.Element | null {
const { startExport } = useActions(exportsLogic)
@@ -96,6 +97,7 @@ export function SceneExportDropdownMenu({
void onExportClick({
export_format: item.format,
...(item.insight && { insight: item.insight }),
+ ...(insightShortId && { insightShortId }),
...(item.dashboard && { dashboard: item.dashboard }),
...(item.context && { export_context: item.context }),
})
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3d09e3d24187..a6775f088213 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -286,6 +286,7 @@ export const FEATURE_FLAGS = {
CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analytics
DASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analytics
+ DASHBOARD_EXPORT_NUDGE: 'dashboard-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported a dashboard toward a recurring subscription
DASHBOARD_INLINE_TILE_INSERTION: 'dashboard-inline-tile-insertion', // owner: @MattPua #team-analytics-platform
DASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platform
DASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,new
@@ -344,6 +345,7 @@ export const FEATURE_FLAGS = {
INBOX_SLACK_NOTIFICATIONS: 'inbox-slack-notifications', // owner: #team-self-driving, gates the Slack notifications config card in the inbox
INBOX_WELCOME_REDESIGN: 'inbox-welcome-redesign', // owner: #team-self-driving multivariate=control,test — experiment on the inbox self-driving welcome takeover
INSIGHT_DRAG_TO_ZOOM: 'insight-drag-to-zoom', // owner: @sampennington #team-product-analytics, gates x-axis drag-to-zoom on insight charts (trends today, SQL to follow)
+ INSIGHT_EXPORT_NUDGE: 'insight-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported an insight toward a recurring subscription
INSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,test
JS_SNIPPET_VERSIONING: 'js-snippet-versioning', // owner: #team-client-libraries
LEGACY_OAUTH_RECONNECT_WARNING: 'legacy-oauth-reconnect-warning', // owner: @jabahamondes #team-web-analytics — kill-switch for the retiring-OAuth-app reconnect banner
diff --git a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
index b13c78f926da..382416032024 100644
--- a/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
+++ b/frontend/src/lib/lemon-ui/LemonToast/LemonToast.tsx
@@ -1,5 +1,5 @@
import posthog from 'posthog-js'
-import { toast, type ToastOptions } from 'react-toastify'
+import { toast, type ToastOptions, type UpdateOptions } from 'react-toastify'
import { IconCheckCircle, IconInfo, IconWarning, IconX } from '@posthog/icons'
@@ -24,7 +24,7 @@ export function ToastCloseButton({ closeToast }: { closeToast?: () => void }): J
)
}
-interface ToastButton {
+export interface ToastButton {
label: string
action: (() => void) | (() => Promise<void>)
dataAttr?: string
@@ -52,6 +52,8 @@ export const EMAIL_SUPPORT_BUTTON: ToastButton = {
},
}
+const successIcon = (): JSX.Element => (isChristmas() ? <IconGift className="text-green-600" /> : <IconCheckCircle />)
+
export interface ToastContentProps {
type: 'info' | 'success' | 'warning' | 'error'
message: string | JSX.Element
@@ -59,24 +61,36 @@ export interface ToastContentProps {
id?: number | string
}
+export function ToastActionButton({
+ button,
+ toastId,
+}: {
+ button: ToastButton
+ toastId?: number | string
+}): JSX.Element {
+ return (
+ <LemonButton
+ onClick={() => {
+ void button.action()
+ // Not lemonToast.dismiss: that marks the id cancelled so the next toast reusing it
+ // is swallowed, and ids are a hash of the message, so the same error would go quiet.
+ toast.dismiss(toastId)
+ }}
+ type="secondary"
+ size="small"
+ data-attr={button.dataAttr}
+ className={button.className}
+ >
+ {button.label}
+ </LemonButton>
+ )
+}
+
export function ToastContent({ type, message, button, id }: ToastContentProps): JSX.Element {
return (
<div className="flex items-center" data-attr={`${type}-toast`}>
<span className="grow overflow-hidden text-ellipsis">{message}</span>
- {button && (
- <LemonButton
- onClick={() => {
- void button.action()
- toast.dismiss(id)
- }}
- type="secondary"
- size="small"
- data-attr={button.dataAttr}
- className={button.className}
- >
- {button.label}
- </LemonButton>
- )}
+ {button && <ToastActionButton button={button} toastId={id} />}
</div>
)
}
@@ -160,7 +174,7 @@ export const lemonToast = {
return
}
toast.success(<ToastContent type="success" message={message} button={button} id={id} />, {
- icon: isChristmas() ? <IconGift className="text-green-600" /> : <IconCheckCircle />,
+ icon: successIcon(),
...options,
})
})
@@ -220,25 +234,31 @@ export const lemonToast = {
},
promise(
promise: Promise<any>,
- messages: { pending: string | JSX.Element; success: string | JSX.Element; error: string | JSX.Element },
+ messages: {
+ pending: string | JSX.Element
+ /** A function is called when the promise settles, so it can read state that changed while it ran. */
+ success: string | JSX.Element | ((data?: string) => string | JSX.Element)
+ error: string | JSX.Element
+ },
{ button, ...toastOptions }: ToastOptionsWithButton = {}
): Promise<any> {
- // Promise toasts always get random IDs (unless explicitly provided) because
- // different operations often share identical pending text like "Saving..."
const options = ensureToastId(toastOptions, 'promise')
+ const id = options.toastId
// see https://fkhadra.github.io/react-toastify/promise
return toast.promise<string | undefined, ToastError>(
promise,
{
pending: {
- render: <ToastContent type="info" message={messages.pending} button={button} />,
+ render: <ToastContent type="info" message={messages.pending} button={button} id={id} />,
icon: <Spinner />,
},
success: {
render: ({ data }) => {
- return <ToastContent type="success" message={data || messages.success} button={button} />
+ const success =
+ typeof messages.success === 'function' ? messages.success(data) : data || messages.success
+ return <ToastContent type="success" message={success} button={button} id={id} />
},
- icon: isChristmas() ? <IconGift className="text-green-600" /> : <IconCheckCircle />,
+ icon: successIcon(),
},
error: {
render: ({ data }) => {
@@ -247,6 +267,7 @@ export const lemonToast = {
type="error"
message={withIncidentNote(data?.message || messages.error)}
button={button}
+ id={id}
/>
)
},
@@ -256,6 +277,28 @@ export const lemonToast = {
options
)
},
+ updateToSuccess(
+ id: number | string,
+ message: string | JSX.Element,
+ { button, ...toastOptions }: ToastOptionsWithButton = {}
+ ): void {
+ toast.update(id, {
+ render: <ToastContent type="success" message={message} button={button} id={id} />,
+ type: 'success',
+ icon: successIcon(),
+ // react-toastify drops null props so the container's defaults apply again. This is the
+ // same reset its own promise() resolver does when leaving the loading state.
+ isLoading: null,
+ autoClose: null,
+ closeOnClick: null,
+ closeButton: null,
+ draggable: null,
+ ...toastOptions,
+ } as UpdateOptions)
+ },
+ isActive(id: number | string): boolean {
+ return toast.isActive(id)
+ },
dismiss(id?: number | string): void {
// If a toast was created in this tick but hasn't been registered yet (due to
// queueMicrotask deferral), mark the ID as cancelled so the microtask skips it.
diff --git a/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsx b/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsx
index f20710996ee6..24bfa479d349 100644
--- a/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsx
+++ b/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsx
@@ -1,5 +1,3 @@
-import { router } from 'kea-router'
-
import { IconBell } from '@posthog/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -7,23 +5,13 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import {
SUBSCRIPTION_PREFILL_PARAMS,
- urlForSubscription,
-} from 'products/subscriptions/frontend/components/Subscriptions/utils'
+ openSubscriptionFromNudge,
+} from 'products/subscriptions/frontend/components/Subscriptions/subscriptionNudge'
export function dashboardSubscribeNudgeToastId(dashboardId: number): string {
return `dashboard-subscribe-nudge-${dashboardId}`
}
-// Deliberately free of any kea logic dependency: the sticky toast can outlive the dashboard
-// scene (and its keyed logic), so the CTA only touches globals — the router and the toast itself.
-export function onDashboardSubscribeNudgeToastCta(dashboardId: number): void {
- lemonToast.dismiss(dashboardSubscribeNudgeToastId(dashboardId))
- router.actions.push(urlForSubscription('new', { dashboardId }), {
- [SUBSCRIPTION_PREFILL_PARAMS.param]: SUBSCRIPTION_PREFILL_PARAMS.nudge,
- [SUBSCRIPTION_PREFILL_PARAMS.viaParam]: SUBSCRIPTION_PREFILL_PARAMS.viaToast,
- })
-}
-
export function DashboardSubscribeNudgeToast({
dashboardId,
dashboardName,
@@ -47,7 +35,15 @@ export function DashboardSubscribeNudgeToast({
type="primary"
size="small"
data-attr="dashboard-subscribe-nudge-toast-cta"
- onClick={() => onDashboardSubscribeNudgeToastCta(dashboardId)}
+ onClick={() =>
+ openSubscriptionFromNudge(
+ { dashboardId },
+ {
+ toastId: dashboardSubscribeNudgeToastId(dashboardId),
+ via: SUBSCRIPTION_PREFILL_PARAMS.viaToast,
+ }
+ )
+ }
>
Set up subscription
</LemonButton>
diff --git a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.ts b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.ts
index 222bc0851760..77575ad0ec6f 100644
--- a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.ts
@@ -1,7 +1,9 @@
import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { createElement } from 'react'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import posthog from 'lib/posthog-typed'
@@ -34,7 +36,7 @@ import {
DASHBOARD_VIEW_LOG_WINDOW_MS,
MAX_TRACKED_DASHBOARDS,
} from './dashboardSubscribeNudgeStoreLogic'
-import { DashboardSubscribeNudgeToast, onDashboardSubscribeNudgeToastCta } from './DashboardSubscribeNudgeToast'
+import { DashboardSubscribeNudgeToast } from './DashboardSubscribeNudgeToast'
jest.mock('lib/posthog-typed', () => ({
__esModule: true,
@@ -316,7 +318,15 @@ describe('dashboardSubscribeNudgeLogic', () => {
})
it('the toast CTA dismisses the toast and routes to the prefilled new-subscription form', () => {
- onDashboardSubscribeNudgeToastCta(DASHBOARD_ID)
+ render(
+ createElement(DashboardSubscribeNudgeToast, {
+ dashboardId: DASHBOARD_ID,
+ dashboardName: 'Test dashboard',
+ viewCount7d: DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD,
+ })
+ )
+ fireEvent.click(screen.getByText('Set up subscription'))
+ cleanup()
expect(lemonToast.dismiss).toHaveBeenCalledWith(`dashboard-subscribe-nudge-${DASHBOARD_ID}`)
expect(router.values.location.pathname).toMatch(new RegExp(`/dashboard/${DASHBOARD_ID}/subscriptions/new$`))
diff --git a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.ts b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.ts
index 016fc580ef0b..4ee94aab56ec 100644
--- a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.ts
@@ -29,9 +29,12 @@ import { userLogic } from 'scenes/userLogic'
import { AvailableFeature, DashboardPlacement } from '~/types'
+import {
+ fetchHasSubscriptionForDashboard,
+ fetchTeamSubscriptionCount,
+} from 'products/subscriptions/frontend/components/Subscriptions/subscriptionQueries'
import { subscriptionsLogic } from 'products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic'
-import { isFreeTierCreateAtLimit } from 'products/subscriptions/frontend/components/Subscriptions/views/EditSubscription'
-import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
+import { canNudgeToSubscribe } from 'products/subscriptions/frontend/components/Subscriptions/utils'
import type { DashboardType, QueryBasedInsightModel } from '../../types'
import type { DashboardViewLog } from './dashboardSubscribeNudgeStoreLogic'
@@ -204,19 +207,11 @@ export const dashboardSubscribeNudgeLogic = kea<dashboardSubscribeNudgeLogicType
null as boolean | null,
{
loadExistingSubscription: async (_?: unknown, breakpoint?: BreakPointFunction) => {
- // If a subscriptionsLogic for this dashboard is already mounted (e.g. the
- // subscriptions modal was opened), reuse its data instead of refetching.
const mounted = subscriptionsLogic.findMounted({ dashboardId: props.dashboardId })
if (mounted && !mounted.values.subscriptionsLoading) {
return mounted.values.subscriptions.length > 0
}
- // limit=1 keeps the payload tiny; `count` reflects the dashboard's full total.
- const response = await subscriptionsList(String(getCurrentTeamId()), {
- dashboard: props.dashboardId,
- limit: 1,
- })
- breakpoint?.()
- return (response.count ?? 0) > 0
+ return await fetchHasSubscriptionForDashboard(props.dashboardId, breakpoint)
},
},
],
@@ -224,11 +219,8 @@ export const dashboardSubscribeNudgeLogic = kea<dashboardSubscribeNudgeLogicType
freeTierSubscriptionCount: [
null as number | null,
{
- loadFreeTierSubscriptionCount: async (_?: unknown, breakpoint?: BreakPointFunction) => {
- const response = await subscriptionsList(String(getCurrentTeamId()), { limit: 1 })
- breakpoint?.()
- return response.count ?? 0
- },
+ loadFreeTierSubscriptionCount: async (_?: unknown, breakpoint?: BreakPointFunction) =>
+ await fetchTeamSubscriptionCount(breakpoint),
},
],
nudgeNotification: [
@@ -290,15 +282,10 @@ export const dashboardSubscribeNudgeLogic = kea<dashboardSubscribeNudgeLogicType
isDashboardEligible: boolean
): boolean => isPastViewThreshold && !isSuppressed && !isNotified && isDashboardEligible,
],
- // Paid orgs are never limited. Free-tier orgs must have room under the free-tier cap —
- // and unlike EditSubscription (where a null count fails open because the user explicitly
- // asked and the backend is the hard gate), a proactive nudge fails closed on an unknown
- // count: don't advertise an action we can't confirm they can complete.
isWithinSubscriptionLimit: [
(s) => [s.hasSubscriptionsFeature, s.freeTierSubscriptionCount],
(hasSubscriptionsFeature: boolean, freeTierSubscriptionCount: number | null): boolean =>
- hasSubscriptionsFeature ||
- (freeTierSubscriptionCount !== null && !isFreeTierCreateAtLimit(freeTierSubscriptionCount)),
+ canNudgeToSubscribe(hasSubscriptionsFeature, freeTierSubscriptionCount),
],
isEligible: [
(s) => [s.isCandidate, s.hasExistingSubscription, s.isWithinSubscriptionLimit],
diff --git a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
index 2a50a69277eb..5d1da79d0091 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightPanelActions.tsx
@@ -152,6 +152,7 @@ export function InsightPanelActions({ insightLogicProps }: { insightLogicProps:
{canExport ? (
<SceneExportDropdownMenu
+ insightShortId={insight.short_id}
dropdownMenuItems={[
{
format: ExporterFormat.PNG,
diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
index fd5840b5934a..c6b8b0efae2d 100644
--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx
@@ -275,6 +275,7 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: In
startExport({
export_format: ExporterFormat.PNG,
insight: insight.id,
+ insightShortId: insight.short_id,
export_context: exportContext,
})
}
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 177494926487..41fcff34b0e8 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -3585,8 +3585,8 @@ class DashboardsViewSet(
resource_type="dashboard",
resource_id=str(dashboard.pk),
# Query params mirror SUBSCRIPTION_PREFILL_PARAMS in
- # products/subscriptions/frontend/components/Subscriptions/utils.tsx, which
- # consumes them to prefill the new-subscription form.
+ # products/subscriptions/frontend/components/Subscriptions/subscriptionNudge.ts,
+ # which consumes them to prefill the new-subscription form.
source_url=f"/dashboard/{dashboard.pk}/subscriptions/new?prefill=nudge&via=notification",
)
)
diff --git a/products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast.tsx b/products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast.tsx
new file mode 100644
index 000000000000..3abe6f437b82
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/exportNudge/ExportNudgeToast.tsx
@@ -0,0 +1,96 @@
+import { useState } from 'react'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { ToastActionButton, ToastButton } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import {
+ ExportNudgeCandidate,
+ claimExportNudge,
+ subjectNoun,
+ subscriptionTargetFor,
+} from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic'
+import {
+ SUBSCRIPTION_PREFILL_PARAMS,
+ openSubscriptionFromNudge,
+} from 'products/subscriptions/frontend/components/Subscriptions/subscriptionNudge'
+
+/**
+ * Builds the toast's message. The offer rides along until it is followed, and lays the toast's own
+ * action out beside its CTA so the two sit on one row. `toastId` is required because that action
+ * closes its own toast, and closing without one closes every toast on screen.
+ */
+export type ExportNudgeMessage = (
+ headline: string,
+ toastId: number | string,
+ action?: ToastButton
+) => string | JSX.Element
+
+function subjectLabel(candidate: ExportNudgeCandidate): JSX.Element | string {
+ if (candidate.name) {
+ return <span className="italic">{candidate.name}</span>
+ }
+ return subjectNoun(candidate.subject)
+}
+
+/**
+ * The toast on screen is static children, so flipping a flag in the closure does not remove this
+ * button from it. Its own state does, which also stops a second click reporting a second follow.
+ */
+function SubscribeButton({ onFollow }: { onFollow: () => void }): JSX.Element {
+ const [followed, setFollowed] = useState(false)
+ return (
+ <LemonButton
+ type="primary"
+ size="small"
+ data-attr="export-nudge-toast-cta"
+ disabledReason={followed ? 'Opening the subscription form' : undefined}
+ onClick={() => {
+ setFollowed(true)
+ onFollow()
+ }}
+ >
+ Subscribe
+ </LemonButton>
+ )
+}
+
+export function claimExportNudgeMessage(candidate: ExportNudgeCandidate): ExportNudgeMessage | null {
+ if (!claimExportNudge(candidate.subject)) {
+ return null
+ }
+
+ let accepted = false
+ return (headline: string, toastId: number | string, action?: ToastButton) => {
+ // One layout either way. Following the offer only takes the offer away: this message still
+ // owns the row, so it keeps rendering the export's own action, and a file waiting to be
+ // downloaded does not lose its button.
+ if (accepted && !action) {
+ return headline
+ }
+ return (
+ <span className="flex flex-col items-start gap-1.5 min-w-0">
+ <span>{headline}</span>
+ {!accepted && (
+ <span className="text-xs text-secondary leading-snug">
+ Want this on a schedule? We can send you a copy of {subjectLabel(candidate)} every week.
+ </span>
+ )}
+ {/* The toast body gives every button a horizontal margin, which would push this row
+ off the text above it and space the two buttons apart. */}
+ <span className="flex flex-wrap items-center gap-2 *:m-0!">
+ {!accepted && (
+ <SubscribeButton
+ onFollow={() => {
+ accepted = true
+ openSubscriptionFromNudge(subscriptionTargetFor(candidate.subject), {
+ via: SUBSCRIPTION_PREFILL_PARAMS.viaExport,
+ })
+ }}
+ />
+ )}
+ {action && <ToastActionButton button={action} toastId={toastId} />}
+ </span>
+ </span>
+ )
+ }
+}
diff --git a/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic.test.tsx b/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic.test.tsx
new file mode 100644
index 000000000000..f60b80a68727
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic.test.tsx
@@ -0,0 +1,294 @@
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import posthog from 'lib/posthog-typed'
+import { userLogic } from 'scenes/userLogic'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
+import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { AvailableFeature, InsightShortId, UserType } from '~/types'
+
+import { subscriptionsLogic } from 'products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic'
+import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
+
+import {
+ claimExportNudge,
+ exportNudgeLogic,
+ lookUpExportNudge,
+ resolveExportNudgeEligibility,
+} from './exportNudgeLogic'
+import { ExportNudgeSubject } from './exportNudgeSubject'
+import { claimExportNudgeMessage } from './ExportNudgeToast'
+
+jest.mock('lib/posthog-typed', () => ({
+ __esModule: true,
+ default: { capture: jest.fn(), captureRaw: jest.fn() },
+}))
+
+jest.mock('products/subscriptions/frontend/generated/api', () => ({
+ subscriptionsList: jest.fn(),
+}))
+
+const mockSubscriptionsList = subscriptionsList as jest.Mock
+
+const DASHBOARD_ID = 1
+const INSIGHT_SHORT_ID = '11' as InsightShortId
+const DASHBOARD: ExportNudgeSubject = { kind: 'dashboard', dashboardId: DASHBOARD_ID }
+const INSIGHT: ExportNudgeSubject = { kind: 'insight', insightShortId: INSIGHT_SHORT_ID }
+
+const USER_WITH_SUBSCRIPTIONS_FEATURE: UserType = {
+ ...MOCK_DEFAULT_USER,
+ organization: {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: [{ key: AvailableFeature.SUBSCRIPTIONS, name: 'Subscriptions' }],
+ },
+}
+
+function capturesOf(event: string): any[][] {
+ return [...(posthog.capture as jest.Mock).mock.calls, ...(posthog.captureRaw as jest.Mock).mock.calls].filter(
+ ([name]) => name === event
+ )
+}
+
+describe('exportNudgeLogic', () => {
+ let logic: ReturnType<typeof exportNudgeLogic.build>
+
+ function mockSubscriptionCounts({
+ subjectCount,
+ teamCount = 0,
+ }: {
+ subjectCount: number
+ teamCount?: number
+ }): void {
+ mockSubscriptionsList.mockImplementation((_teamId: string, params?: Record<string, unknown>) =>
+ Promise.resolve(
+ params?.dashboard || params?.insight
+ ? { count: subjectCount, results: [] }
+ : { count: teamCount, results: [] }
+ )
+ )
+ }
+
+ beforeEach(() => {
+ window.localStorage.clear()
+ mockSubscriptionsList.mockReset()
+ mockSubscriptionCounts({ subjectCount: 0 })
+ useMocks({
+ get: {
+ // Resolves the short id the insight subscription filter needs.
+ '/api/environments/:team_id/insights': () => [200, { results: [{ id: 11, short_id: '11' }] }],
+ '/api/environments/:team_id/subscriptions': () => [200, { results: [], count: 0 }],
+ },
+ })
+ initKeaTests()
+ userLogic.mount()
+ userLogic.actions.loadUserSuccess(USER_WITH_SUBSCRIPTIONS_FEATURE)
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.DASHBOARD_EXPORT_NUDGE]: 'test',
+ [FEATURE_FLAGS.INSIGHT_EXPORT_NUDGE]: 'test',
+ })
+ logic = exportNudgeLogic()
+ logic.mount()
+ ;(posthog.capture as jest.Mock).mockClear()
+ ;(posthog.captureRaw as jest.Mock).mockClear()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ window.localStorage.clear()
+ })
+
+ async function considerNudge(subject: ExportNudgeSubject = DASHBOARD): Promise<boolean> {
+ const candidate = await resolveExportNudgeEligibility(subject)
+ return !!candidate && claimExportNudge(subject)
+ }
+
+ it.each([
+ ['dashboard', DASHBOARD, { kind: 'dashboard', dashboard_id: DASHBOARD_ID }],
+ ['insight', INSIGHT, { kind: 'insight', insight_short_id: INSIGHT_SHORT_ID }],
+ ])('nudges an eligible %s exporter in the test variant', async (kind, subject, eventProperties) => {
+ expect(await considerNudge(subject)).toBe(true)
+
+ expect(capturesOf(`${kind} export nudge shown`)).toEqual([[`${kind} export nudge shown`, eventProperties]])
+ })
+
+ it('does not nudge in the control variant', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_EXPORT_NUDGE]: 'control' })
+
+ // The variant is read only by the second half, so a control exporter still resolves as a
+ // candidate. Every other check has to run before the flag read reports exposure.
+ expect(await resolveExportNudgeEligibility(DASHBOARD)).toMatchObject({ subject: DASHBOARD })
+ expect(claimExportNudge(DASHBOARD)).toBe(false)
+ })
+
+ it('nudges the same dashboard again on a later export', async () => {
+ expect(await considerNudge()).toBe(true)
+ expect(await considerNudge()).toBe(true)
+
+ expect(capturesOf('dashboard export nudge shown')).toHaveLength(2)
+ })
+
+ it.each([
+ ['dashboard', DASHBOARD],
+ ['insight', INSIGHT],
+ ])('does not nudge a %s that already has a subscription', async (_kind, subject) => {
+ mockSubscriptionCounts({ subjectCount: 1 })
+
+ expect(await considerNudge(subject)).toBe(false)
+ })
+
+ it('asks again once the subscription that retired the offer is gone', async () => {
+ mockSubscriptionCounts({ subjectCount: 1 })
+ expect(await considerNudge()).toBe(false)
+
+ // Nothing is remembered across the two exports: the subscription check is the only gate, so
+ // deleting the subscription brings the offer back.
+ mockSubscriptionCounts({ subjectCount: 0 })
+ expect(await considerNudge()).toBe(true)
+ })
+
+ it('offers nothing it cannot check when the insight cannot be resolved', async () => {
+ // A deleted insight, or an export racing its creation: the short id resolves to nothing, so
+ // there is no subscription to check against.
+ useMocks({ get: { '/api/environments/:team_id/insights': () => [200, { results: [] }] } })
+
+ expect(await considerNudge(INSIGHT)).toBe(true)
+ // The lookup answers "no subscription", which is what an unresolvable insight means here.
+ expect(mockSubscriptionsList).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ insight: expect.anything() })
+ )
+ })
+
+ describe('answering without a request', () => {
+ // The scene mounts subscriptionsLogic to render the subscribe button's count badge, so most
+ // exports can put the offer in their toast from the first frame instead of fetching again.
+ it('is eligible off the subscriptions the scene already loaded', async () => {
+ const sceneLogic = subscriptionsLogic({ dashboardId: DASHBOARD_ID })
+ sceneLogic.mount()
+ await expectLogic(sceneLogic).toFinishAllListeners()
+
+ expect(lookUpExportNudge(DASHBOARD)).toMatchObject({ status: 'eligible' })
+ expect(mockSubscriptionsList).not.toHaveBeenCalled()
+
+ sceneLogic.unmount()
+ })
+
+ it('says so when nothing is loaded, rather than guessing', () => {
+ expect(lookUpExportNudge(DASHBOARD)).toEqual({ status: 'unknown' })
+ })
+
+ it('is ineligible when the loaded subscriptions include one for the subject', () => {
+ const sceneLogic = subscriptionsLogic({ dashboardId: DASHBOARD_ID })
+ sceneLogic.mount()
+ sceneLogic.actions.loadSubscriptionsSuccess([{ id: 1 } as any])
+
+ expect(lookUpExportNudge(DASHBOARD)).toEqual({ status: 'ineligible' })
+
+ sceneLogic.unmount()
+ })
+ })
+
+ describe('free-tier subscription limit', () => {
+ beforeEach(() => {
+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER) // no available features -> free tier
+ })
+
+ it.each([
+ [0, true],
+ [SubscriptionFreeTierLimit.COUNT - 1, true],
+ [SubscriptionFreeTierLimit.COUNT, false],
+ ])('with %i existing team subscriptions, nudges=%s', async (teamCount, nudges) => {
+ mockSubscriptionCounts({ subjectCount: 0, teamCount })
+
+ expect(await considerNudge()).toBe(nudges)
+ })
+ })
+
+ describe('failed eligibility checks', () => {
+ beforeEach(() => {
+ silenceKeaLoadersErrors()
+ })
+
+ afterEach(() => {
+ resumeKeaLoadersErrors()
+ })
+
+ it('fails closed and reports when the subscription check breaks', async () => {
+ mockSubscriptionsList.mockRejectedValue({ name: 'ApiError', status: 500, message: 'boom' })
+
+ expect(await considerNudge()).toBe(false)
+ expect(capturesOf('export nudge check failed')).toHaveLength(1)
+ expect(capturesOf('export nudge check failed')[0][1]).toMatchObject({
+ dashboard_id: DASHBOARD_ID,
+ step: 'check',
+ })
+ })
+
+ it('fails closed and reports when the free-tier count breaks', async () => {
+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
+ mockSubscriptionsList.mockRejectedValue({ name: 'ApiError', status: 500, message: 'boom' })
+
+ expect(await considerNudge()).toBe(false)
+ expect(capturesOf('export nudge check failed')[0][1]).toMatchObject({ step: 'limit' })
+ })
+ })
+
+ describe('nudge toast message', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('renders nothing for an exporter outside the test variant', () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_EXPORT_NUDGE]: 'control' })
+
+ expect(claimExportNudgeMessage({ subject: DASHBOARD, name: 'Weekly numbers' })).toBeNull()
+ })
+
+ it.each([
+ [DASHBOARD, 'Weekly numbers', `/dashboard/${DASHBOARD_ID}/subscriptions/new`],
+ [INSIGHT, null, `/insights/${INSIGHT_SHORT_ID}/subscriptions/new`],
+ ])('the CTA routes to the prefilled new-subscription form', (subject, name, path) => {
+ const message = claimExportNudgeMessage({ subject, name })
+ render(<>{message!('Export complete!', 'export-toast')}</>)
+
+ fireEvent.click(screen.getByText('Subscribe'))
+
+ expect(router.values.location.pathname).toMatch(new RegExp(`${path}$`))
+ expect(router.values.searchParams).toMatchObject({ prefill: 'nudge', via: 'export' })
+ })
+
+ it('reports one follow even if the CTA is clicked twice', () => {
+ // A toast held open by an undelivered file keeps this button on screen, and the offer
+ // only leaves on a later frame, so nothing else stops a second click.
+ const message = claimExportNudgeMessage({ subject: DASHBOARD, name: 'Weekly numbers' })
+ render(<>{message!('Export complete!', 'export-toast')}</>)
+
+ const push = jest.spyOn(router.actions, 'push')
+ const cta = screen.getByText('Subscribe')
+ fireEvent.click(cta)
+ fireEvent.click(cta)
+
+ expect(push).toHaveBeenCalledTimes(1)
+ push.mockRestore()
+ })
+
+ it('drops the offer from later frames once it has been followed', () => {
+ const message = claimExportNudgeMessage({ subject: DASHBOARD, name: 'Weekly numbers' })
+ render(<>{message!('Preparing export…', 'export-toast')}</>)
+ fireEvent.click(screen.getByText('Subscribe'))
+ cleanup()
+
+ // The export settles into its own message rather than asking a second time.
+ expect(message!('Export complete!', 'export-toast')).toEqual('Export complete!')
+ })
+ })
+})
diff --git a/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic.ts b/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic.ts
new file mode 100644
index 000000000000..fb2230029e45
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeLogic.ts
@@ -0,0 +1,261 @@
+import { BreakPointFunction, MakeLogicType, connect, kea, listeners, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import posthog from 'lib/posthog-typed'
+import { userLogic } from 'scenes/userLogic'
+
+import { dashboardsModel } from '~/models/dashboardsModel'
+import { AvailableFeature } from '~/types'
+
+import { ExportNudgeSubject } from 'products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeSubject'
+import {
+ fetchHasSubscriptionForDashboard,
+ fetchHasSubscriptionForInsight,
+ fetchTeamSubscriptionCount,
+} from 'products/subscriptions/frontend/components/Subscriptions/subscriptionQueries'
+import { subscriptionsLogic } from 'products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic'
+import {
+ SubscriptionBaseProps,
+ canNudgeToSubscribe,
+} from 'products/subscriptions/frontend/components/Subscriptions/utils'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface exportNudgeLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
+ freeTierSubscriptionCount: number | null
+ freeTierSubscriptionCountLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface exportNudgeLogicActions {
+ loadFreeTierSubscriptionCount: (_?: unknown) => unknown
+ loadFreeTierSubscriptionCountFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFreeTierSubscriptionCountSuccess: (
+ freeTierSubscriptionCount: number,
+ payload?: unknown
+ ) => {
+ freeTierSubscriptionCount: number
+ payload?: unknown
+ }
+}
+
+export type exportNudgeLogicType = MakeLogicType<exportNudgeLogicValues, exportNudgeLogicActions>
+
+export const exportNudgeLogic = kea<exportNudgeLogicType>([
+ path(['products', 'subscriptions', 'exportNudgeLogic']),
+ connect(() => ({
+ values: [featureFlagLogic, ['featureFlags'], userLogic, ['hasAvailableFeature']],
+ })),
+ loaders(() => ({
+ // The `load` prefix puts this on initKea's ERROR_FILTER_ALLOW_LIST, so a failed background
+ // check doesn't toast at a user who never asked for anything.
+ freeTierSubscriptionCount: [
+ null as number | null,
+ {
+ loadFreeTierSubscriptionCount: async (_?: unknown, breakpoint?: BreakPointFunction) =>
+ await fetchTeamSubscriptionCount(breakpoint),
+ },
+ ],
+ })),
+ listeners(() => ({
+ loadFreeTierSubscriptionCountFailure: ({ error, errorObject }) => {
+ // A failed count excludes a free-tier user, and the readout cannot tell that apart from
+ // being at the limit unless it is recorded.
+ captureExportNudgeCheckFailed('limit', {
+ error_name: errorObject?.name,
+ error_status: errorObject?.status,
+ error_message: error,
+ })
+ },
+ })),
+])
+
+export interface ExportNudgeCandidate {
+ subject: ExportNudgeSubject
+ name: string | null
+}
+
+export type ExportNudgeLookup =
+ | { status: 'eligible'; candidate: ExportNudgeCandidate }
+ | { status: 'ineligible' }
+ | { status: 'unknown' }
+
+type SubjectOfKind<K extends ExportNudgeSubject['kind']> = Extract<ExportNudgeSubject, { kind: K }>
+
+interface SubjectKindSupport<K extends ExportNudgeSubject['kind']> {
+ /** Event names are spelled out so the string a metric is configured against can be grepped. */
+ flag: keyof FeatureFlagsSet
+ shownEvent: string
+ /** How the subscriptions code addresses this subject: the mounted logic's key, and the CTA url. */
+ target: (subject: SubjectOfKind<K>) => SubscriptionBaseProps
+ hasSubscription: (subject: SubjectOfKind<K>) => Promise<boolean>
+ eventProperties: (subject: SubjectOfKind<K>) => Record<string, string | number>
+ /** Null where the app holds no name for it, and the offer's copy falls back on `noun`. */
+ name: (subject: SubjectOfKind<K>) => string | null
+ noun: string
+}
+
+// One place to add a subject kind. Everything that differs per kind lives here rather than in a
+// ternary at each call site.
+const SUBJECT_SUPPORT: { [K in ExportNudgeSubject['kind']]: SubjectKindSupport<K> } = {
+ dashboard: {
+ flag: FEATURE_FLAGS.DASHBOARD_EXPORT_NUDGE,
+ shownEvent: 'dashboard export nudge shown',
+ target: (subject) => ({ dashboardId: subject.dashboardId }),
+ hasSubscription: (subject) => fetchHasSubscriptionForDashboard(subject.dashboardId),
+ eventProperties: (subject) => ({ kind: subject.kind, dashboard_id: subject.dashboardId }),
+ name: (subject) => dashboardsModel.findMounted()?.values.rawDashboards[subject.dashboardId]?.name ?? null,
+ noun: 'this dashboard',
+ },
+ insight: {
+ flag: FEATURE_FLAGS.INSIGHT_EXPORT_NUDGE,
+ shownEvent: 'insight export nudge shown',
+ target: (subject) => ({ insightShortId: subject.insightShortId }),
+ hasSubscription: (subject) => fetchHasSubscriptionForInsight(subject.insightShortId),
+ eventProperties: (subject) => ({ kind: subject.kind, insight_short_id: subject.insightShortId }),
+ // There is no light-weight model of insights to read a name from, and importing the insight
+ // scene here would put it in every export surface's import graph.
+ name: () => null,
+ noun: 'this insight',
+ },
+}
+
+// Each entry is written against its own variant, so it needs no casts. This lookup is the one place
+// that widens back to the union, which is sound because the record is keyed by the same `kind`.
+const supportFor = (subject: ExportNudgeSubject): SubjectKindSupport<ExportNudgeSubject['kind']> =>
+ SUBJECT_SUPPORT[subject.kind] as unknown as SubjectKindSupport<ExportNudgeSubject['kind']>
+
+/** What the offer calls a subject with no name of its own. */
+export function subjectNoun(subject: ExportNudgeSubject): string {
+ return supportFor(subject).noun
+}
+
+export function captureExportNudgeCheckFailed(
+ step: 'limit' | 'check' | 'timeout' | 'toast-gone',
+ properties: Record<string, unknown> = {}
+): void {
+ posthog.capture('export nudge check failed', { step, ...properties })
+}
+
+// Mounted on first use, so exports of anything else do not pay for it, and left mounted so the
+// free-tier count survives between exports.
+function mountedExportNudgeLogic(): typeof exportNudgeLogic {
+ if (!exportNudgeLogic.isMounted()) {
+ exportNudgeLogic.mount()
+ }
+ return exportNudgeLogic
+}
+
+export function exportNudgeEventProperties(subject: ExportNudgeSubject): Record<string, string | number> {
+ return supportFor(subject).eventProperties(subject)
+}
+
+export function subscriptionTargetFor(subject: ExportNudgeSubject): SubscriptionBaseProps {
+ return supportFor(subject).target(subject)
+}
+
+// The subscribe button on both scenes shows a count, which mounts subscriptionsLogic and loads the
+// subject's subscriptions, so most exports need no request of their own. The count only renders for
+// teams that have the feature, so free-tier teams fall through to the network check. A failed load
+// reads as an empty list here, so this path cannot fail closed.
+function loadedSubscriptionCount(subject: ExportNudgeSubject): number | null {
+ const mounted = subscriptionsLogic.findMounted(subscriptionTargetFor(subject))
+ if (!mounted || mounted.values.subscriptionsLoading) {
+ return null
+ }
+ return mounted.values.subscriptions.length
+}
+
+/** `unknown` means the team's count has not loaded, which is not the same as being over the cap. */
+function subscriptionLimitStatus(): 'within' | 'exceeded' | 'unknown' {
+ const { values } = mountedExportNudgeLogic()
+ const hasFeature = values.hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS)
+ if (!hasFeature && values.freeTierSubscriptionCount === null) {
+ return 'unknown'
+ }
+ return canNudgeToSubscribe(hasFeature, values.freeTierSubscriptionCount) ? 'within' : 'exceeded'
+}
+
+/** null means the check itself failed. */
+async function fetchHasExistingSubscription(subject: ExportNudgeSubject): Promise<boolean | null> {
+ try {
+ return await supportFor(subject).hasSubscription(subject)
+ } catch (error: any) {
+ captureExportNudgeCheckFailed('check', {
+ ...exportNudgeEventProperties(subject),
+ error_name: error?.name,
+ error_status: error?.status,
+ error_message: error?.message ?? String(error),
+ })
+ return null
+ }
+}
+
+export function lookUpExportNudge(subject: ExportNudgeSubject): ExportNudgeLookup {
+ const limitStatus = subscriptionLimitStatus()
+ if (limitStatus !== 'within') {
+ return { status: limitStatus === 'unknown' ? 'unknown' : 'ineligible' }
+ }
+
+ const subscriptionCount = loadedSubscriptionCount(subject)
+ if (subscriptionCount === null) {
+ return { status: 'unknown' }
+ }
+ if (subscriptionCount > 0) {
+ return { status: 'ineligible' }
+ }
+ return { status: 'eligible', candidate: { subject, name: supportFor(subject).name(subject) } }
+}
+
+/** Runs alongside the export, for a subject whose scene had not already loaded the answer. */
+export async function resolveExportNudgeEligibility(subject: ExportNudgeSubject): Promise<ExportNudgeCandidate | null> {
+ const { values, asyncActions } = mountedExportNudgeLogic()
+ if (!values.hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS) && values.freeTierSubscriptionCount === null) {
+ await asyncActions.loadFreeTierSubscriptionCount()
+ }
+ const limitStatus = subscriptionLimitStatus()
+ if (limitStatus === 'unknown') {
+ // A second export can dispatch the same loader and breakpoint this one, so the count can
+ // still be unresolved here without any request failing. Reported because every other way
+ // the offer disappears reports a step.
+ captureExportNudgeCheckFailed('limit', exportNudgeEventProperties(subject))
+ return null
+ }
+ if (limitStatus !== 'within') {
+ return null
+ }
+
+ const hasExistingSubscription = await fetchHasExistingSubscription(subject)
+ if (hasExistingSubscription === null) {
+ return null // fail closed on a broken check
+ }
+ if (hasExistingSubscription) {
+ return null
+ }
+
+ return { subject, name: supportFor(subject).name(subject) }
+}
+
+/**
+ * Last gate, run as the nudge renders so an exposure is never reported for a toast nobody saw.
+ * Returns whether this exporter is in the treatment.
+ */
+export function claimExportNudge(subject: ExportNudgeSubject): boolean {
+ const { values } = mountedExportNudgeLogic()
+ // Reading the flag fires the exposure event, so it goes last, once every other check passed.
+ if (values.featureFlags[supportFor(subject).flag] !== 'test') {
+ return false
+ }
+
+ posthog.captureRaw(supportFor(subject).shownEvent, exportNudgeEventProperties(subject))
+ return true
+}
diff --git a/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeSubject.ts b/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeSubject.ts
new file mode 100644
index 000000000000..f995ad751f52
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/exportNudge/exportNudgeSubject.ts
@@ -0,0 +1,33 @@
+import { ExporterFormat, InsightShortId } from '~/types'
+
+/** What an export is of. Exports of anything else are never nudged. */
+export type ExportNudgeSubject =
+ | { kind: 'dashboard'; dashboardId: number }
+ | { kind: 'insight'; insightShortId: InsightShortId }
+
+// A subscription renders a PNG, so only a PNG export is worth answering with the offer of one.
+// Someone taking a CSV wants the rows. The backend side of that is the PNG in
+// products/exports/backend/temporal/subscriptions/activities.py.
+const SUBSCRIBABLE_EXPORT_FORMATS: ExporterFormat[] = [ExporterFormat.PNG]
+
+/**
+ * Only a dashboard or a saved insight can be subscribed to, so a recording, a heatmap, a cohort, a
+ * data table or a billing report has no subject. Nor does an insight exported from a surface that
+ * does not pass its short id, since there would be no subscription page to send anyone to.
+ */
+export function exportNudgeSubjectFor(exportData: {
+ export_format: ExporterFormat
+ dashboard?: number | null
+ insightShortId?: InsightShortId
+}): ExportNudgeSubject | null {
+ if (!SUBSCRIBABLE_EXPORT_FORMATS.includes(exportData.export_format)) {
+ return null
+ }
+ if (exportData.dashboard) {
+ return { kind: 'dashboard', dashboardId: exportData.dashboard }
+ }
+ if (exportData.insightShortId) {
+ return { kind: 'insight', insightShortId: exportData.insightShortId }
+ }
+ return null
+}
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index f94b2d84748c..b8974d35537b 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -287,50 +287,104 @@ describe('subscriptionLogic', () => {
expect(promptLogic.values.subscription[field as 'frequency' | 'prompt']).toBe(expected)
})
- it.each<[string, string, string]>([
- // The notification's source_url carries via=notification; the transient toast via=toast.
- // Absent via defaults to notification for safety.
- ['?prefill=nudge&via=notification', 'notification', 'notification link'],
- ['?prefill=nudge&via=toast', 'toast', 'toast button'],
- ['?prefill=nudge', 'notification', 'legacy link without via'],
- ])('prefills the form from %s and reports the click (via=%s, %s)', async (search, expectedVia) => {
- // The nudge notification can be clicked days later in a fresh session, so the prefill is
- // built from the URL param + logic context, not from any preexisting kea state.
- const prefilledLogic = subscriptionLogic({
- dashboardId: 9,
- dashboardName: 'Key metrics',
- id: 'new',
- })
- prefilledLogic.mount()
+ it('prefills an insight nudge with its own title and event', async () => {
+ const insightLogic = subscriptionLogic({ insightShortId: '123' as InsightShortId, id: 'new' })
+ insightLogic.mount()
- router.actions.push(`/dashboard/9/subscriptions/new${search}`)
- await expectLogic(prefilledLogic).toFinishListeners()
+ router.actions.push('/insights/123/subscriptions/new?prefill=nudge&via=export')
+ await expectLogic(insightLogic).toFinishListeners()
- expect(prefilledLogic.values.subscription).toMatchObject({
- title: 'Key metrics weekly digest',
+ // An insight reaches this route without a name in hand, so its subscription is named for
+ // the schedule rather than for the insight.
+ expect(insightLogic.values.subscription).toMatchObject({
+ title: 'Weekly digest',
target_value: MOCK_DEFAULT_USER.email,
- frequency: 'weekly',
- target_type: 'email',
})
- expect(prefilledLogic.values.subscriptionChanged).toBe(true)
- const clickedCaptures = (): any[][] =>
- (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === 'dashboard subscribe nudge clicked')
- expect(clickedCaptures()).toEqual([
- ['dashboard subscribe nudge clicked', { dashboard_id: 9, prefilled: true, via: expectedVia }],
+ expect((posthog.capture as jest.Mock).mock.calls.filter(([name]) => name.endsWith('nudge clicked'))).toEqual([
+ [
+ 'insight export nudge clicked',
+ { kind: 'insight', insight_short_id: '123', prefilled: true, via: 'export' },
+ ],
])
- // The params are consumed on apply, so refreshing the resulting URL neither re-captures
- // the click nor re-applies a stale prefill.
- expect(prefilledLogic.values.subscription.title).toBe('Key metrics weekly digest')
- expect(router.values.searchParams.prefill).toBeUndefined()
- expect(router.values.searchParams.via).toBeUndefined()
- router.actions.push(router.values.location.pathname)
- await expectLogic(prefilledLogic).toFinishListeners()
- expect(clickedCaptures()).toHaveLength(1)
+ insightLogic.unmount()
+ })
- prefilledLogic.unmount()
+ it('leaves a nudge for another subject to the form that owns it', async () => {
+ // The route pattern matches any subject's page, so every mounted form sees this navigation.
+ // One prefilling for someone else's nudge would discard what its own user had typed.
+ const dashboardForm = subscriptionLogic({ dashboardId: 9, dashboardName: 'Key metrics', id: 'new' })
+ const insightForm = subscriptionLogic({ insightShortId: '123' as InsightShortId, id: 'new' })
+ dashboardForm.mount()
+ insightForm.mount()
+
+ router.actions.push('/dashboard/9/subscriptions/new?prefill=nudge&via=export')
+ await expectLogic(dashboardForm).toFinishListeners()
+ await expectLogic(insightForm).toFinishListeners()
+
+ expect(dashboardForm.values.subscription).toMatchObject({ title: 'Key metrics weekly digest' })
+ expect(insightForm.values.subscription.title).toBeUndefined()
+ expect(insightForm.values.subscriptionChanged).toBe(false)
+ // One click, reported once, against the dashboard.
+ expect((posthog.capture as jest.Mock).mock.calls.filter(([name]) => name.endsWith('nudge clicked'))).toEqual([
+ ['dashboard export nudge clicked', { kind: 'dashboard', dashboard_id: 9, prefilled: true, via: 'export' }],
+ ])
+
+ dashboardForm.unmount()
+ insightForm.unmount()
})
+ it.each<[string, string, string, string]>([
+ // The notification's source_url carries via=notification; the transient toast via=toast.
+ // Absent via defaults to notification for safety. The export nudge is its own experiment,
+ // so it reports a separate event instead of another `via` value on this one.
+ ['?prefill=nudge&via=notification', 'notification', 'dashboard subscribe nudge clicked', 'notification link'],
+ ['?prefill=nudge&via=toast', 'toast', 'dashboard subscribe nudge clicked', 'toast button'],
+ ['?prefill=nudge&via=export', 'export', 'dashboard export nudge clicked', 'export toast button'],
+ ['?prefill=nudge', 'notification', 'dashboard subscribe nudge clicked', 'legacy link without via'],
+ ])(
+ 'prefills the form from %s and reports the click (via=%s, %s, %s)',
+ async (search, expectedVia, expectedEvent) => {
+ // The nudge notification can be clicked days later in a fresh session, so the prefill is
+ // built from the URL param + logic context, not from any preexisting kea state.
+ const prefilledLogic = subscriptionLogic({
+ dashboardId: 9,
+ dashboardName: 'Key metrics',
+ id: 'new',
+ })
+ prefilledLogic.mount()
+
+ router.actions.push(`/dashboard/9/subscriptions/new${search}`)
+ await expectLogic(prefilledLogic).toFinishListeners()
+
+ expect(prefilledLogic.values.subscription).toMatchObject({
+ title: 'Key metrics weekly digest',
+ target_value: MOCK_DEFAULT_USER.email,
+ frequency: 'weekly',
+ target_type: 'email',
+ })
+ expect(prefilledLogic.values.subscriptionChanged).toBe(true)
+ // Matches on both nudge events, so a `via` routed to the wrong one fails here rather
+ // than silently moving a conversion between the two experiments.
+ const clickedCaptures = (): any[][] =>
+ (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name.endsWith('nudge clicked'))
+ expect(clickedCaptures()).toEqual([
+ [expectedEvent, { kind: 'dashboard', dashboard_id: 9, prefilled: true, via: expectedVia }],
+ ])
+
+ // The params are consumed on apply, so refreshing the resulting URL neither re-captures
+ // the click nor re-applies a stale prefill.
+ expect(prefilledLogic.values.subscription.title).toBe('Key metrics weekly digest')
+ expect(router.values.searchParams.prefill).toBeUndefined()
+ expect(router.values.searchParams.via).toBeUndefined()
+ router.actions.push(router.values.location.pathname)
+ await expectLogic(prefilledLogic).toFinishListeners()
+ expect(clickedCaptures()).toHaveLength(1)
+
+ prefilledLogic.unmount()
+ }
+ )
+
it.each<[string, boolean, boolean]>([
// The prefill marks the form "changed" so Create is enabled, but the user never touched it —
// navigating away must not pop the discard-changes prompt.
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
index 99822e386a35..d95a3615e516 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts
@@ -10,6 +10,7 @@ import { dayjs } from 'lib/dayjs'
import { recordRecentSlackChannel, slackChannelId } from 'lib/integrations/slackChannel'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { isEmail } from 'lib/utils/url'
import { getInsightId } from 'scenes/insights/utils'
@@ -28,14 +29,15 @@ import type { SubscriptionResourceType, UserBasicType, WeekdayType } from '../..
import type { OrganizationType, UserType } from '../../../../../frontend/src/types'
import type { AIPromptConfigApi } from '../../generated/api.schemas'
import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'
+import { SUBSCRIPTION_PREFILL_PARAMS } from './subscriptionNudge'
import { subscriptionsLogic } from './subscriptionsLogic'
-import {
- ALL_DAYS,
- AI_PROMPT_MAX_LENGTH,
- SUBSCRIPTION_PREFILL_PARAMS,
- SubscriptionBaseProps,
- urlForSubscription,
-} from './utils'
+import { ALL_DAYS, AI_PROMPT_MAX_LENGTH, SubscriptionBaseProps, urlForSubscription } from './utils'
+
+// Spelled out rather than interpolated, so the event a metric is configured against is greppable.
+const EXPORT_NUDGE_CLICKED_EVENTS = {
+ dashboard: 'dashboard export nudge clicked',
+ insight: 'insight export nudge clicked',
+} as const
function validatePrompt(
resource_type: SubscriptionType['resource_type'],
@@ -837,11 +839,16 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
if (searchParams.resource_type === SubscriptionResourceTypes.AiPrompt) {
actions.setSubscriptionValue('resource_type', SubscriptionResourceTypes.AiPrompt)
}
- // ?prefill=nudge is set by the subscribe-nudge notification / toast, possibly opened in a
- // fresh session days later — the prefill is built here from URL + context, not kea state.
+ const nudgeSubject = props.dashboardId ? 'dashboard' : props.insightShortId ? 'insight' : null
+ // The route pattern matches any subject's page, so without this a logic keyed to another
+ // insight or dashboard prefills and reports the click for someone else's nudge.
+ const isOwnSubject =
+ removeProjectIdIfPresent(router.values.location.pathname) ===
+ urlForSubscription('new', { dashboardId: props.dashboardId, insightShortId: props.insightShortId })
if (
searchParams[SUBSCRIPTION_PREFILL_PARAMS.param] === SUBSCRIPTION_PREFILL_PARAMS.nudge &&
- props.dashboardId
+ nudgeSubject &&
+ isOwnSubject
) {
// Consume the params before applying: the replace synchronously re-enters this
// handler (resetting the form to plain defaults), and it also makes a later refresh
@@ -853,7 +860,12 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
} = router.values.searchParams
router.actions.replace(router.values.location.pathname, restSearchParams, router.values.hashParams)
const prefill: Partial<SubscriptionType> = {
- title: `${props.dashboardName || 'Dashboard'} weekly digest`,
+ // Only dashboards reach this route with a name in hand, so an insight's
+ // subscription is named for the schedule rather than for the insight.
+ title:
+ nudgeSubject === 'dashboard'
+ ? `${props.dashboardName || 'Dashboard'} weekly digest`
+ : 'Weekly digest',
...(values.user?.email ? { target_value: values.user.email } : {}),
}
// Goes through setSubscriptionValues (not the loaded baseline) so the form is marked
@@ -861,15 +873,20 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
// default, so "Create subscription" doesn't require an extra no-op edit to enable.
actions.setSubscriptionValues(prefill)
cache.prefillBaseline = { ...NEW_SUBSCRIPTION, ...prefill }
- // Both toast and notification links enter the nudge flow through this route.
- posthog.capture('dashboard subscribe nudge clicked', {
- dashboard_id: props.dashboardId,
- prefilled: !!values.user?.email,
- via:
- searchParams[SUBSCRIPTION_PREFILL_PARAMS.viaParam] === SUBSCRIPTION_PREFILL_PARAMS.viaToast
- ? SUBSCRIPTION_PREFILL_PARAMS.viaToast
- : SUBSCRIPTION_PREFILL_PARAMS.viaNotification,
- })
+ const via = searchParams[SUBSCRIPTION_PREFILL_PARAMS.viaParam]
+ posthog.capture(
+ via === SUBSCRIPTION_PREFILL_PARAMS.viaExport
+ ? EXPORT_NUDGE_CLICKED_EVENTS[nudgeSubject]
+ : 'dashboard subscribe nudge clicked',
+ {
+ kind: nudgeSubject,
+ ...(nudgeSubject === 'dashboard'
+ ? { dashboard_id: props.dashboardId }
+ : { insight_short_id: props.insightShortId }),
+ prefilled: !!values.user?.email,
+ via: via ?? SUBSCRIPTION_PREFILL_PARAMS.viaNotification,
+ }
+ )
}
if (searchParams.target_type) {
actions.setSubscriptionValue('target_type', searchParams.target_type)
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionNudge.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionNudge.ts
new file mode 100644
index 000000000000..a5b946275192
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionNudge.ts
@@ -0,0 +1,34 @@
+import { router } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { SubscriptionBaseProps, urlForSubscription } from './utils'
+
+export const SUBSCRIPTION_PREFILL_PARAMS = {
+ param: 'prefill',
+ nudge: 'nudge',
+ viaParam: 'via',
+ viaToast: 'toast',
+ viaNotification: 'notification',
+ viaExport: 'export',
+} as const
+
+export type SubscriptionNudgeVia =
+ | typeof SUBSCRIPTION_PREFILL_PARAMS.viaToast
+ | typeof SUBSCRIPTION_PREFILL_PARAMS.viaExport
+
+export function openSubscriptionFromNudge(
+ target: SubscriptionBaseProps,
+ { toastId, via }: { toastId?: string; via: SubscriptionNudgeVia }
+): void {
+ // A toast whose only content is the nudge has nothing left to offer once it is followed, and
+ // names itself here to be closed. One shared with an export passes no id: that toast still
+ // carries the export's download, which dismissing would discard.
+ if (toastId) {
+ lemonToast.dismiss(toastId)
+ }
+ router.actions.push(urlForSubscription('new', target), {
+ [SUBSCRIPTION_PREFILL_PARAMS.param]: SUBSCRIPTION_PREFILL_PARAMS.nudge,
+ [SUBSCRIPTION_PREFILL_PARAMS.viaParam]: via,
+ })
+}
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionQueries.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionQueries.ts
new file mode 100644
index 000000000000..5be777d366e0
--- /dev/null
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionQueries.ts
@@ -0,0 +1,41 @@
+import { BreakPointFunction } from 'kea'
+
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { getInsightId } from 'scenes/insights/utils'
+
+import { InsightShortId } from '~/types'
+
+import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
+
+export async function fetchTeamSubscriptionCount(breakpoint?: BreakPointFunction): Promise<number> {
+ const response = await subscriptionsList(String(getCurrentTeamId()), { limit: 1 })
+ breakpoint?.()
+ return response.count ?? 0
+}
+
+export async function fetchHasSubscriptionForDashboard(
+ dashboardId: number,
+ breakpoint?: BreakPointFunction
+): Promise<boolean> {
+ const response = await subscriptionsList(String(getCurrentTeamId()), { dashboard: dashboardId, limit: 1 })
+ breakpoint?.()
+ return (response.count ?? 0) > 0
+}
+
+export async function fetchHasSubscriptionForInsightId(
+ insightId: number,
+ breakpoint?: BreakPointFunction
+): Promise<boolean> {
+ const response = await subscriptionsList(String(getCurrentTeamId()), { insight: insightId, limit: 1 })
+ breakpoint?.()
+ return (response.count ?? 0) > 0
+}
+
+export async function fetchHasSubscriptionForInsight(
+ insightShortId: InsightShortId,
+ breakpoint?: BreakPointFunction
+): Promise<boolean> {
+ const insightId = await getInsightId(insightShortId)
+ breakpoint?.()
+ return insightId ? await fetchHasSubscriptionForInsightId(insightId, breakpoint) : false
+}
diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
index f25a276431b3..480790441be4 100644
--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
@@ -1,4 +1,7 @@
+import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'
+
import {
+ canNudgeToSubscribe,
getAiSubscriptionGate,
getNextDeliveryDate,
selectedDaysToDayPickerLabel,
@@ -157,3 +160,16 @@ describe('getAiSubscriptionGate', () => {
expect(getAiSubscriptionGate({ ...base, ...overrides })).toMatchObject(expected)
})
})
+
+describe('canNudgeToSubscribe', () => {
+ // isFreeTierCreateAtLimit fails open on an unknown count so the form still renders. The nudge
+ // wants the opposite, so the null case is decided here rather than left to that helper.
+ it.each([
+ ['a paid plan is nudged whatever the free-tier count says', true, null, true],
+ ['free tier with room left is nudged', false, 0, true],
+ ['free tier at the limit is not nudged', false, SubscriptionFreeTierLimit.COUNT, false],
+ ['an unknown count is not nudged', false, null, false],
+ ] as const)('%s', (_label, hasSubscriptionsFeature, freeTierSubscriptionCount, expected) => {
+ expect(canNudgeToSubscribe(hasSubscriptionsFeature, freeTierSubscriptionCount)).toBe(expected)
+ })
+})
diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsx
index 65201e9b4ba3..bebacd74db1f 100644
--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx
@@ -7,11 +7,25 @@ import { IconSlack } from 'lib/lemon-ui/icons'
import { range } from 'lib/utils/arrays'
import { urls } from 'scenes/urls'
-import { SubscriptionAIPromptMaxLength } from '~/queries/schema/schema-general'
+import { SubscriptionAIPromptMaxLength, SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'
import { InsightShortId, SubscriptionType, WeekdayType } from '~/types'
export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERS
+export function isFreeTierCreateAtLimit(subscriptionCount: number | null): boolean {
+ return subscriptionCount !== null && subscriptionCount >= SubscriptionFreeTierLimit.COUNT
+}
+
+export function canNudgeToSubscribe(
+ hasSubscriptionsFeature: boolean,
+ freeTierSubscriptionCount: number | null
+): boolean {
+ return (
+ hasSubscriptionsFeature ||
+ (freeTierSubscriptionCount !== null && !isFreeTierCreateAtLimit(freeTierSubscriptionCount))
+ )
+}
+
export interface SubscriptionBaseProps {
dashboardId?: number
insightShortId?: InsightShortId
@@ -29,20 +43,6 @@ export const urlForSubscriptions = ({ dashboardId, insightShortId }: Subscriptio
return urls.subscriptions()
}
-/**
- * Deep-link params the subscribe-nudge uses to open the new-subscription form prefilled.
- * Single source of truth shared by the producer (dashboard toast) and the consumer (this
- * logic's urlToAction). The backend notification's source_url must mirror these — see the
- * comment on source_url in products/dashboards/backend/api/dashboard.py.
- */
-export const SUBSCRIPTION_PREFILL_PARAMS = {
- param: 'prefill',
- nudge: 'nudge',
- viaParam: 'via',
- viaToast: 'toast',
- viaNotification: 'notification',
-} as const
-
export const urlForSubscription = (
id: number | 'new',
{ dashboardId, insightShortId }: SubscriptionBaseProps
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.gate.test.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.gate.test.tsx
index 7693905189a8..e934cbe3eda8 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.gate.test.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.gate.test.tsx
@@ -1,6 +1,6 @@
import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'
-import { isFreeTierCreateAtLimit } from './EditSubscription'
+import { isFreeTierCreateAtLimit } from '../utils'
const LIMIT = SubscriptionFreeTierLimit.COUNT
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
index c61492588e53..18c990003bfc 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
@@ -60,6 +60,7 @@ import {
weekdayOptions,
WEEKDAYS,
AI_PROMPT_MAX_LENGTH,
+ isFreeTierCreateAtLimit,
} from '../utils'
// Shown wherever AI subscriptions are gated off (org hasn't approved AI data
@@ -197,11 +198,6 @@ interface EditSubscriptionProps {
onDelete: () => void
}
-// A null count (loading or fetch failed) fails open — the backend POST check is the hard limit.
-export function isFreeTierCreateAtLimit(subscriptionCount: number | null): boolean {
- return subscriptionCount !== null && subscriptionCount >= SubscriptionFreeTierLimit.COUNT
-}
-
export function EditSubscription(props: EditSubscriptionProps): JSX.Element {
const { hasAvailableFeature } = useValues(userLogic)
const isCreating = props.id === 'new'