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.

6.5 KB
Raw Blame
import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'

import { DashboardType, InsightShortId } from '~/types'

import { insightsList } from 'products/product_analytics/frontend/generated/api'

/** How many saved insights the picker offers before the user narrows them by search. */
const INSIGHT_OPTIONS_LIMIT = 100

export type NewSubscriptionTargetKind = 'insight' | 'dashboard' | 'ai'

/**
 * What a subscription started from the subscriptions scene will send. Everywhere else
 * the target comes from the page the user was already on, so it needs picking here.
 */
export type NewSubscriptionTarget =
    | { kind: 'insight'; shortId: InsightShortId; name: string }
    | { kind: 'dashboard'; id: number; name: string }
    | { kind: 'ai' }

export interface NewSubscriptionInsightOption {
    shortId: InsightShortId
    name: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSubscriptionTargetLogicValues {
    dashboard: DashboardType | null
    dashboardLoading: boolean
    insightOptions: NewSubscriptionInsightOption[]
    insightOptionsLoading: boolean
    insightSearch: string
    kind: NewSubscriptionTargetKind | null
    target: NewSubscriptionTarget | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newSubscriptionTargetLogicActions {
    chooseAiPrompt: () => {
        value: true
    }
    chooseDashboard: (
        id: number,
        name: string
    ) => {
        id: number
        name: string
    }
    chooseInsight: (
        shortId: InsightShortId,
        name: string
    ) => {
        name: string
        shortId: InsightShortId
    }
    loadDashboard: (id: number) => number
    loadDashboardFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDashboardSuccess: (
        dashboard: DashboardType,
        payload?: number
    ) => {
        dashboard: DashboardType
        payload?: number
    }
    loadInsightOptions: (_: any) => any
    loadInsightOptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInsightOptionsSuccess: (
        insightOptions: NewSubscriptionInsightOption[],
        payload?: any
    ) => {
        insightOptions: NewSubscriptionInsightOption[]
        payload?: any
    }
    reset: () => {
        value: true
    }
    setInsightSearch: (search: string) => {
        search: string
    }
    setKind: (kind: NewSubscriptionTargetKind) => {
        kind: NewSubscriptionTargetKind
    }
}

export type newSubscriptionTargetLogicType = MakeLogicType<
    newSubscriptionTargetLogicValues,
    newSubscriptionTargetLogicActions
>

export const newSubscriptionTargetLogic = kea<newSubscriptionTargetLogicType>([
    path(['products', 'subscriptions', 'frontend', 'scenes', 'newSubscriptionTargetLogic']),
    actions({
        setKind: (kind: NewSubscriptionTargetKind) => ({ kind }),
        setInsightSearch: (search: string) => ({ search }),
        chooseInsight: (shortId: InsightShortId, name: string) => ({ shortId, name }),
        chooseDashboard: (id: number, name: string) => ({ id, name }),
        chooseAiPrompt: true,
        reset: true,
    }),
    loaders(({ values }) => ({
        insightOptions: [
            [] as NewSubscriptionInsightOption[],
            {
                loadInsightOptions: async (_, breakpoint): Promise<NewSubscriptionInsightOption[]> => {
                    await breakpoint(300)
                    const response = await insightsList(String(getCurrentTeamId()), {
                        saved: true,
                        basic: true,
                        limit: INSIGHT_OPTIONS_LIMIT,
                        search: values.insightSearch || undefined,
                    })
                    breakpoint()
                    return (response.results || [])
                        .filter((insight) => !!insight.short_id)
                        .map((insight) => ({
                            shortId: insight.short_id as InsightShortId,
                            name: insight.name || insight.derived_name || 'Untitled',
                        }))
                },
            },
        ],
        dashboard: [
            null as DashboardType | null,
            {
                // The creation form needs the dashboard's tiles to offer its insights, which the
                // app-wide dashboard list does not carry. `api.dashboards.get` returns the shape
                // that form is typed on; the generated client returns its own dashboard type.
                loadDashboard: async (id: number): Promise<DashboardType> => await api.dashboards.get(id),
            },
        ],
    })),
    reducers({
        kind: [
            null as NewSubscriptionTargetKind | null,
            {
                setKind: (_, { kind }) => kind,
                reset: () => null,
            },
        ],
        insightSearch: [
            '',
            {
                setInsightSearch: (_, { search }) => search,
                setKind: () => '',
                reset: () => '',
            },
        ],
        target: [
            null as NewSubscriptionTarget | null,
            {
                chooseInsight: (_, { shortId, name }) => ({ kind: 'insight', shortId, name }),
                chooseDashboard: (_, { id, name }) => ({ kind: 'dashboard', id, name }),
                chooseAiPrompt: () => ({ kind: 'ai' }),
                reset: () => null,
            },
        ],
        dashboard: [
            null as DashboardType | null,
            {
                reset: () => null,
            },
        ],
    }),
    listeners(({ actions }) => ({
        setKind: ({ kind }) => {
            if (kind === 'insight') {
                actions.loadInsightOptions(null)
            }
        },
        setInsightSearch: () => {
            actions.loadInsightOptions(null)
        },
        // The creation form is rendered from the dashboard itself, so fetch it as soon as
        // it is picked rather than making the form wait for a mount effect.
        chooseDashboard: ({ id }) => {
            actions.loadDashboard(id)
        },
        loadDashboardFailure: () => {
            lemonToast.error('Could not load that dashboard. Pick it again, or try another one.')
            actions.reset()
        },
    })),
])