:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import {
MakeLogicType,
BreakPointFunction,
afterMount,
connect,
kea,
key,
listeners,
path,
props,
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'lib/posthog-typed'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { userLogic } from 'scenes/userLogic'
import { AvailableFeature, DashboardPlacement } from '~/types'
import type { DashboardType } from '~/types'
import {
fetchHasSubscriptionForDashboard,
fetchTeamSubscriptionCount,
} from 'products/subscriptions/frontend/components/Subscriptions/subscriptionQueries'
import { subscriptionsLogic } from 'products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic'
import { canNudgeToSubscribe } from 'products/subscriptions/frontend/components/Subscriptions/utils'
import {
dashboardNudgeScopeKey,
dashboardSubscribeNudgeStoreLogic,
freshTimestamps,
} from './dashboardSubscribeNudgeStoreLogic'
import type { DashboardViewLog } from './dashboardSubscribeNudgeStoreLogic'
import { showDashboardSubscribeNudgeToast } from './DashboardSubscribeNudgeToast'
import { dashboardsSubscribeNudgeCreate } from './generated/api'
import type { DashboardSubscribeNudgeResponseApi } from './generated/api.schemas'
export const DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD = 3
export interface DashboardSubscribeNudgeLogicProps {
dashboardId: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardSubscribeNudgeLogicValues {
canEditDashboard: boolean // dashboardLogic
dashboard: DashboardType | null // dashboardLogic
placement: DashboardPlacement // dashboardLogic
notifiedDashboardIds: number[] // dashboardSubscribeNudgeStoreLogic
suppressedDashboardIds: number[] // dashboardSubscribeNudgeStoreLogic
viewLog: DashboardViewLog // dashboardSubscribeNudgeStoreLogic
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
freeTierSubscriptionCount: number | null
freeTierSubscriptionCountLoading: boolean
hasExistingSubscription: boolean | null
hasExistingSubscriptionLoading: boolean
hasSubscriptionsFeature: boolean
isCandidate: boolean
isDashboardEligible: boolean
isEligible: boolean
isNotified: boolean
isPastViewThreshold: boolean
isSuppressed: boolean
isWithinSubscriptionLimit: boolean
nudgeNotification: DashboardSubscribeNudgeResponseApi | null
nudgeNotificationLoading: boolean
showNudge: boolean
viewCount7d: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardSubscribeNudgeLogicActions {
reportDashboardViewed: () => {
value: true
} // dashboardLogic
markDashboardNotified: (dashboardId: number) => {
dashboardId: number
} // dashboardSubscribeNudgeStoreLogic
recordDashboardView: (dashboardId: number) => {
dashboardId: number
} // dashboardSubscribeNudgeStoreLogic
suppressDashboardNudge: (dashboardId: number) => {
dashboardId: number
} // dashboardSubscribeNudgeStoreLogic
loadExistingSubscription: (_?: unknown) => unknown
loadExistingSubscriptionFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadExistingSubscriptionSuccess: (
hasExistingSubscription: boolean,
payload?: unknown
) => {
hasExistingSubscription: boolean
payload?: unknown
}
loadFreeTierSubscriptionCount: (_?: unknown) => unknown
loadFreeTierSubscriptionCountFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadFreeTierSubscriptionCountSuccess: (
freeTierSubscriptionCount: number,
payload?: unknown
) => {
freeTierSubscriptionCount: number
payload?: unknown
}
sendNudgeNotification: (_?: unknown) => unknown
sendNudgeNotificationFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
sendNudgeNotificationSuccess: (
nudgeNotification: DashboardSubscribeNudgeResponseApi,
payload?: unknown
) => {
nudgeNotification: DashboardSubscribeNudgeResponseApi
payload?: unknown
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardSubscribeNudgeLogicMeta {
key: number
__keaTypeGenInternalSelectorTypes: {
viewCount7d: (viewLog: DashboardViewLog, arg: any) => number
isPastViewThreshold: (viewCount7d: number) => boolean
isSuppressed: (suppressedDashboardIds: number[], arg: any) => boolean
isNotified: (notifiedDashboardIds: number[], arg: any) => boolean
isDashboardEligible: (
dashboard: DashboardType | null,
canEditDashboard: boolean,
placement: DashboardPlacement
) => boolean
hasSubscriptionsFeature: (
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
) => boolean
isCandidate: (
isPastViewThreshold: boolean,
isSuppressed: boolean,
isNotified: boolean,
isDashboardEligible: boolean
) => boolean
isWithinSubscriptionLimit: (
hasSubscriptionsFeature: boolean,
freeTierSubscriptionCount: number | null
) => boolean
isEligible: (
isCandidate: boolean,
hasExistingSubscription: boolean | null,
isWithinSubscriptionLimit: boolean
) => boolean
showNudge: (isEligible: boolean) => boolean
}
}
export type dashboardSubscribeNudgeLogicType = MakeLogicType<
dashboardSubscribeNudgeLogicValues,
dashboardSubscribeNudgeLogicActions,
DashboardSubscribeNudgeLogicProps,
dashboardSubscribeNudgeLogicMeta
>
export const dashboardSubscribeNudgeLogic = kea<dashboardSubscribeNudgeLogicType>([
path((key) => ['scenes', 'dashboard', 'dashboardSubscribeNudgeLogic', key]),
props({} as DashboardSubscribeNudgeLogicProps),
key((props) => props.dashboardId),
connect((props: DashboardSubscribeNudgeLogicProps) => ({
values: [
dashboardLogic({ id: props.dashboardId }),
['dashboard', 'canEditDashboard', 'placement'],
userLogic,
['hasAvailableFeature'],
dashboardSubscribeNudgeStoreLogic({ scope: dashboardNudgeScopeKey() }),
['viewLog', 'suppressedDashboardIds', 'notifiedDashboardIds'],
],
actions: [
dashboardLogic({ id: props.dashboardId }),
['reportDashboardViewed'],
dashboardSubscribeNudgeStoreLogic({ scope: dashboardNudgeScopeKey() }),
['recordDashboardView', 'suppressDashboardNudge', 'markDashboardNotified'],
],
})),
loaders(({ props }) => ({
// Whether this dashboard already has a subscription. null = not checked yet. Only fetched
// once every free, local check has passed (`isCandidate`: repeat views, not already
// nudged/dismissed, subscribable dashboard) — most dashboard views make no request at all.
// `load` prefix + initKea's ERROR_FILTER_ALLOW_LIST keep a failed background check from
// toasting at a user who never asked for anything.
hasExistingSubscription: [
null as boolean | null,
{
loadExistingSubscription: async (_?: unknown, breakpoint?: BreakPointFunction) => {
const mounted = subscriptionsLogic.findMounted({ dashboardId: props.dashboardId })
if (mounted && !mounted.values.subscriptionsLoading) {
return mounted.values.subscriptions.length > 0
}
return await fetchHasSubscriptionForDashboard(props.dashboardId, breakpoint)
},
},
],
// This team-wide count is separate from the dashboard-specific subscription check above.
freeTierSubscriptionCount: [
null as number | null,
{
loadFreeTierSubscriptionCount: async (_?: unknown, breakpoint?: BreakPointFunction) =>
await fetchTeamSubscriptionCount(breakpoint),
},
],
nudgeNotification: [
null as DashboardSubscribeNudgeResponseApi | null,
{
sendNudgeNotification: async (_?: unknown, breakpoint?: BreakPointFunction) => {
const response = await dashboardsSubscribeNudgeCreate(String(getCurrentTeamId()), props.dashboardId)
breakpoint?.()
return response
},
},
],
})),
selectors({
viewCount7d: [
(s) => [s.viewLog, (_, props) => props.dashboardId],
(viewLog: DashboardViewLog, dashboardId): number =>
freshTimestamps(viewLog[dashboardId] ?? [], Date.now()).length,
],
isPastViewThreshold: [
(s) => [s.viewCount7d],
(viewCount7d: number): boolean => viewCount7d >= DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD,
],
isSuppressed: [
(s) => [s.suppressedDashboardIds, (_, props) => props.dashboardId],
(suppressedDashboardIds: number[], dashboardId): boolean => suppressedDashboardIds.includes(dashboardId),
],
isNotified: [
(s) => [s.notifiedDashboardIds, (_, props) => props.dashboardId],
(notifiedDashboardIds: number[], dashboardId): boolean => notifiedDashboardIds.includes(dashboardId),
],
// Excludes shared/public/embedded placements — the nudge only makes sense where "set up a
// subscription" is an action the viewer can actually take. Free-tier orgs are NOT excluded
// here: they can create subscriptions up to SubscriptionFreeTierLimit.COUNT, so their gate
// is the count check in `isWithinSubscriptionLimit` instead.
isDashboardEligible: [
(s) => [s.dashboard, s.canEditDashboard, s.placement],
(dashboard: DashboardType | null, canEditDashboard: boolean, placement: DashboardPlacement): boolean =>
!!dashboard && canEditDashboard && placement === DashboardPlacement.Dashboard,
],
hasSubscriptionsFeature: [
(s) => [s.hasAvailableFeature],
(hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean): boolean =>
hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS),
],
// Cheap half of eligibility: needs no API data, so the existing-subscription fetch only
// happens for dashboards that pass this first.
isCandidate: [
(s) => [s.isPastViewThreshold, s.isSuppressed, s.isNotified, s.isDashboardEligible],
(
isPastViewThreshold: boolean,
isSuppressed: boolean,
isNotified: boolean,
isDashboardEligible: boolean
): boolean => isPastViewThreshold && !isSuppressed && !isNotified && isDashboardEligible,
],
isWithinSubscriptionLimit: [
(s) => [s.hasSubscriptionsFeature, s.freeTierSubscriptionCount],
(hasSubscriptionsFeature: boolean, freeTierSubscriptionCount: number | null): boolean =>
canNudgeToSubscribe(hasSubscriptionsFeature, freeTierSubscriptionCount),
],
isEligible: [
(s) => [s.isCandidate, s.hasExistingSubscription, s.isWithinSubscriptionLimit],
(
isCandidate: boolean,
hasExistingSubscription: boolean | null,
isWithinSubscriptionLimit: boolean
): boolean => isCandidate && hasExistingSubscription === false && isWithinSubscriptionLimit,
],
showNudge: [(s) => [s.isEligible], (isEligible: boolean): boolean => isEligible],
}),
listeners(({ actions, values, props }) => ({
reportDashboardViewed: () => {
actions.recordDashboardView(props.dashboardId)
},
recordDashboardView: ({ dashboardId }) => {
if (dashboardId !== props.dashboardId || !values.isCandidate) {
return
}
if (values.hasExistingSubscription === null && !values.hasExistingSubscriptionLoading) {
actions.loadExistingSubscription()
}
if (
!values.hasSubscriptionsFeature &&
values.freeTierSubscriptionCount === null &&
!values.freeTierSubscriptionCountLoading
) {
actions.loadFreeTierSubscriptionCount()
}
},
loadExistingSubscriptionSuccess: ({ hasExistingSubscription }) => {
if (hasExistingSubscription) {
// The viewer clearly knows the feature — permanently stop nudging (and rechecking)
// this dashboard, even if the subscription is later deleted.
actions.suppressDashboardNudge(props.dashboardId)
}
},
loadExistingSubscriptionFailure: ({ error, errorObject }) => {
// Distinguishes a broken eligibility check from genuine ineligibility in the experiment readout.
posthog.capture('dashboard subscribe nudge check failed', {
dashboard_id: props.dashboardId,
step: 'check',
error_name: errorObject?.name,
error_status: errorObject?.status,
error_message: error,
})
},
loadFreeTierSubscriptionCountFailure: ({ error, errorObject }) => {
// A failed count check silently excludes a free-tier user (fail closed) — capture it so
// the readout can tell that apart from genuinely being at the limit.
posthog.capture('dashboard subscribe nudge check failed', {
dashboard_id: props.dashboardId,
step: 'limit',
error_name: errorObject?.name,
error_status: errorObject?.status,
error_message: error,
})
},
sendNudgeNotificationSuccess: ({ nudgeNotification }) => {
if (!nudgeNotification?.created) {
// Nothing was delivered (server dedupe-skip, notifications unavailable, or user
// opt-out) — don't burn the client marker; a later qualifying visit retries and the
// server sentinel still collapses races.
return
}
// Delivered — never request again from this browser.
actions.markDashboardNotified(props.dashboardId)
posthog.capture('dashboard subscribe nudge shown', {
dashboard_id: props.dashboardId,
view_count_7d: values.viewCount7d,
})
showDashboardSubscribeNudgeToast(props.dashboardId, values.dashboard?.name, values.viewCount7d)
},
sendNudgeNotificationFailure: ({ error, errorObject }) => {
// Not marked notified: the next qualifying visit retries.
posthog.capture('dashboard subscribe nudge check failed', {
dashboard_id: props.dashboardId,
step: 'notify',
error_name: errorObject?.name,
error_status: errorObject?.status,
error_message: error,
})
},
})),
subscriptions(({ actions, values, cache }) => ({
// The nudge is requested off the gated eligibility state, which resolves asynchronously once
// the subscription checks complete, so subscribing here catches that late transition.
showNudge: (showNudge: boolean) => {
if (showNudge && !cache.nudgeRequested && !values.nudgeNotificationLoading) {
cache.nudgeRequested = true
actions.sendNudgeNotification()
}
},
})),
afterMount(({ actions, values }) => {
// Covers dashboards already past the threshold from earlier sessions; new views route
// through the recordDashboardView listener instead.
if (!values.isCandidate) {
return
}
if (values.hasExistingSubscription === null) {
actions.loadExistingSubscription()
}
if (!values.hasSubscriptionsFeature && values.freeTierSubscriptionCount === null) {
actions.loadFreeTierSubscriptionCount()
}
}),
])