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.

7.1 KB
Raw Blame
import { MakeLogicType, BreakPointFunction, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { getInsightId } from 'lib/insights/getInsightId'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'

import { SubscriptionType } from '~/types'

import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'
import { toggleSubscriptionEnabled } from './toggleSubscriptionEnabled'
import { SubscriptionsLogicProps } from './utils'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface subscriptionsLogicValues {
    deliveringSubscriptionId: number | null
    insightSubscriptions: SubscriptionType[]
    insightSubscriptionsLoading: boolean
    subscriptions: SubscriptionType[]
    subscriptionsLoading: boolean
    togglingEnabledId: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface subscriptionsLogicActions {
    deleteSubscription: (id: number) => {
        id: number
    }
    deliverSubscription: (id: number) => {
        id: number
    }
    deliverSubscriptionFailure: () => {
        value: true
    }
    deliverSubscriptionSuccess: () => {
        value: true
    }
    loadAllSubscriptions: () => {
        value: true
    }
    loadInsightSubscriptions: (_?: any) => any
    loadInsightSubscriptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInsightSubscriptionsSuccess: (
        insightSubscriptions: SubscriptionType[],
        payload?: any
    ) => {
        insightSubscriptions: SubscriptionType[]
        payload?: any
    }
    loadSubscriptions: (_?: any) => any
    loadSubscriptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSubscriptionsSuccess: (
        subscriptions: SubscriptionType[],
        payload?: any
    ) => {
        subscriptions: SubscriptionType[]
        payload?: any
    }
    setSubscriptionEnabled: (
        id: number,
        enabled: boolean
    ) => {
        enabled: boolean
        id: number
    }
    setSubscriptionEnabledFailure: () => {
        value: true
    }
    setSubscriptionEnabledSuccess: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface subscriptionsLogicMeta {
    key: string
}

export type subscriptionsLogicType = MakeLogicType<
    subscriptionsLogicValues,
    subscriptionsLogicActions,
    SubscriptionsLogicProps,
    subscriptionsLogicMeta
>

export const subscriptionsLogic = kea<subscriptionsLogicType>([
    path(['lib', 'components', 'Subscriptions', 'subscriptionsLogic']),
    props({} as SubscriptionsLogicProps),
    key(({ insightShortId, dashboardId }) =>
        insightShortId ? `insight-${insightShortId}` : dashboardId ? `dashboard-${dashboardId}` : 'subscriptions'
    ),
    actions({
        loadAllSubscriptions: true,
        deleteSubscription: (id: number) => ({ id }),
        deliverSubscription: (id: number) => ({ id }),
        deliverSubscriptionSuccess: true,
        deliverSubscriptionFailure: true,
        setSubscriptionEnabled: (id: number, enabled: boolean) => ({ id, enabled }),
        setSubscriptionEnabledSuccess: true,
        setSubscriptionEnabledFailure: true,
    }),

    loaders(({ props }) => ({
        subscriptions: {
            __default: [] as SubscriptionType[],
            loadSubscriptions: async (_?: any, breakpoint?: BreakPointFunction) => {
                if (!props.dashboardId && !props.insightShortId) {
                    return []
                }

                breakpoint?.()

                const insightId = props.insightShortId ? await getInsightId(props.insightShortId) : undefined
                const response = await api.subscriptions.list({
                    dashboardId: props.dashboardId,
                    insights: insightId ? [insightId] : undefined,
                })
                breakpoint?.()
                return response.results
            },
        },
        // Subscriptions on the dashboard's insight tiles. The backend resolves the tile set from
        // dashboardId, so the count doesn't depend on the dashboard's tiles being loaded client-side.
        insightSubscriptions: {
            __default: [] as SubscriptionType[],
            loadInsightSubscriptions: async (_?: any, breakpoint?: BreakPointFunction) => {
                if (!props.dashboardId) {
                    return []
                }
                breakpoint?.()
                const response = await api.subscriptions.list({ dashboardTiles: props.dashboardId })
                breakpoint?.()
                return response.results
            },
        },
    })),

    reducers({
        subscriptions: {
            deleteSubscription: (state, { id }) => state.filter((a) => a.id !== id),
        },
        insightSubscriptions: {
            deleteSubscription: (state, { id }) => state.filter((a) => a.id !== id),
        },
        deliveringSubscriptionId: [
            null as number | null,
            {
                deliverSubscription: (_, { id }) => id,
                deliverSubscriptionSuccess: () => null,
                deliverSubscriptionFailure: () => null,
            },
        ],
        togglingEnabledId: [
            null as number | null,
            {
                setSubscriptionEnabled: (_, { id }) => id,
                setSubscriptionEnabledSuccess: () => null,
                setSubscriptionEnabledFailure: () => null,
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        loadAllSubscriptions: () => {
            actions.loadSubscriptions()
            actions.loadInsightSubscriptions()
        },
        deleteSubscription: async ({ id }) => {
            await deleteWithUndo({
                endpoint: api.subscriptions.determineDeleteEndpoint(),
                object: { name: 'Subscription', id },
                callback: () => {
                    actions.loadAllSubscriptions()
                },
            })
        },
        deliverSubscription: async ({ id }) => {
            const result = await runSubscriptionTestDelivery(() => api.subscriptions.testDelivery(id))
            if (result === 'success') {
                actions.deliverSubscriptionSuccess()
            } else {
                actions.deliverSubscriptionFailure()
            }
        },
        setSubscriptionEnabled: async ({ id, enabled }) => {
            const owner = values.subscriptions.find((subscription) => subscription.id === id)?.created_by ?? null
            const ok = await toggleSubscriptionEnabled(id, enabled, owner)
            if (ok) {
                actions.setSubscriptionEnabledSuccess()
            } else {
                actions.setSubscriptionEnabledFailure()
            }
        },
        setSubscriptionEnabledSuccess: () => {
            actions.loadAllSubscriptions()
        },
    })),

    afterMount(({ actions }) => {
        actions.loadAllSubscriptions()
    }),
])