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.

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

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import posthog from 'lib/posthog-typed'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { getFiltersFromSubTemplateId } from 'scenes/hog-functions/list/LinkedHogFunctions'
import { projectLogic } from 'scenes/projectLogic'

import { CyclotronJobFiltersType, HogFunctionSubTemplateIdType, HogFunctionType } from '~/types'

const PA_NOTIFICATION_LIST_LIMIT = 500
const PA_NOTIFICATION_SUB_TEMPLATE_IDS: HogFunctionSubTemplateIdType[] = ['pa-rageclick']

function getPANotificationFilterGroups(): CyclotronJobFiltersType[] {
    return PA_NOTIFICATION_SUB_TEMPLATE_IDS.map((id) => getFiltersFromSubTemplateId(id)).filter(
        (filters): filters is CyclotronJobFiltersType => !!filters
    )
}

export type PANotificationUseCase = 'rageclick'

export function getPANotificationUseCase(fn: Pick<HogFunctionType, 'filters'>): PANotificationUseCase | null {
    const events = fn.filters?.events ?? []
    return events.some((event) => event.id === '$rageclick') ? 'rageclick' : null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productAnalyticsNotificationsLogicValues {
    currentProjectId: number | null // projectLogic
    notificationCount: number
    notificationCountLoading: boolean
    notifications: HogFunctionType[]
    notificationsFailed: boolean
    notificationsLoaded: boolean
    notificationsLoading: boolean
    notificationsTruncated: boolean
    pendingDeleteIds: Record<string, true>
    pendingToggleIds: Record<string, true>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productAnalyticsNotificationsLogicActions {
    deleteNotification: (notification: HogFunctionType) => {
        notification: HogFunctionType
    }
    deleteNotificationSettled: (notificationId: string) => {
        notificationId: string
    }
    deleteNotificationStarted: (notificationId: string) => {
        notificationId: string
    }
    loadNotificationCount: () => any
    loadNotificationCountFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNotificationCountSuccess: (
        notificationCount: number,
        payload?: any
    ) => {
        notificationCount: number
        payload?: any
    }
    loadNotifications: () => any
    loadNotificationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNotificationsSuccess: (
        notifications: HogFunctionType[],
        payload?: any
    ) => {
        notifications: HogFunctionType[]
        payload?: any
    }
    setNotifications: (notifications: HogFunctionType[]) => {
        notifications: HogFunctionType[]
    }
    setNotificationsTruncated: (notificationsTruncated: boolean) => {
        notificationsTruncated: boolean
    }
    toggleNotificationEnabled: (
        notificationId: string,
        enabled: boolean
    ) => {
        enabled: boolean
        notificationId: string
    }
    toggleNotificationEnabledSettled: (notificationId: string) => {
        notificationId: string
    }
    toggleNotificationEnabledStarted: (notificationId: string) => {
        notificationId: string
    }
}

export type productAnalyticsNotificationsLogicType = MakeLogicType<
    productAnalyticsNotificationsLogicValues,
    productAnalyticsNotificationsLogicActions
>

export const productAnalyticsNotificationsLogic = kea<productAnalyticsNotificationsLogicType>([
    path(['products', 'product_analytics', 'frontend', 'notifications', 'productAnalyticsNotificationsLogic']),
    connect(() => ({
        values: [projectLogic, ['currentProjectId']],
    })),
    actions({
        toggleNotificationEnabled: (notificationId: string, enabled: boolean) => ({ notificationId, enabled }),
        toggleNotificationEnabledStarted: (notificationId: string) => ({ notificationId }),
        toggleNotificationEnabledSettled: (notificationId: string) => ({ notificationId }),
        deleteNotification: (notification: HogFunctionType) => ({ notification }),
        deleteNotificationStarted: (notificationId: string) => ({ notificationId }),
        deleteNotificationSettled: (notificationId: string) => ({ notificationId }),
        setNotificationsTruncated: (notificationsTruncated: boolean) => ({ notificationsTruncated }),
        // Local (optimistic) writes go through this rather than the loader's success action, which
        // would also clear `notificationsLoading` and hide a reload that is still in flight.
        setNotifications: (notifications: HogFunctionType[]) => ({ notifications }),
    }),
    loaders(({ actions, values }) => ({
        notificationCount: [
            0,
            {
                loadNotificationCount: async (): Promise<number> => {
                    const response = await api.hogFunctions.list({
                        filter_groups: getPANotificationFilterGroups(),
                        types: ['destination'],
                        limit: 1,
                    })

                    return response.count
                },
            },
        ],
        notifications: [
            [] as HogFunctionType[],
            {
                loadNotifications: async (): Promise<HogFunctionType[]> => {
                    const response = await api.hogFunctions.list({
                        filter_groups: getPANotificationFilterGroups(),
                        types: ['destination'],
                        full: true,
                        limit: PA_NOTIFICATION_LIST_LIMIT,
                    })
                    const notificationsTruncated = !!response.next
                    actions.setNotificationsTruncated(notificationsTruncated)
                    if (notificationsTruncated) {
                        lemonToast.warning(
                            `Showing the first ${PA_NOTIFICATION_LIST_LIMIT} notifications. Manage the rest from the data pipelines page.`
                        )
                    }

                    // A reload can race in-flight mutations: a GET that read the DB before a
                    // toggle/delete landed would otherwise revert the toggle or resurrect the
                    // deleted row. Keep the local value for rows with a pending mutation.
                    return response.results
                        .filter((notification) => !notification.deleted && !values.pendingDeleteIds[notification.id])
                        .map((notification) => {
                            if (!values.pendingToggleIds[notification.id]) {
                                return notification
                            }
                            const local = values.notifications.find((item) => item.id === notification.id)
                            return local ? { ...notification, enabled: local.enabled } : notification
                        })
                },
            },
        ],
    })),
    reducers({
        notifications: {
            setNotifications: (_: HogFunctionType[], { notifications }: { notifications: HogFunctionType[] }) =>
                notifications,
        },
        notificationsTruncated: [
            false,
            {
                setNotificationsTruncated: (_, { notificationsTruncated }) => notificationsTruncated,
            },
        ],
        pendingToggleIds: [
            {} as Record<string, true>,
            {
                toggleNotificationEnabledStarted: (state, { notificationId }) => ({
                    ...state,
                    [notificationId]: true,
                }),
                toggleNotificationEnabledSettled: (state, { notificationId }) => {
                    const nextState = { ...state }
                    delete nextState[notificationId]
                    return nextState
                },
            },
        ],
        pendingDeleteIds: [
            {} as Record<string, true>,
            {
                deleteNotificationStarted: (state, { notificationId }) => ({
                    ...state,
                    [notificationId]: true,
                }),
                deleteNotificationSettled: (state, { notificationId }) => {
                    const nextState = { ...state }
                    delete nextState[notificationId]
                    return nextState
                },
            },
        ],
        notificationsFailed: [
            false,
            {
                loadNotifications: () => false,
                loadNotificationsSuccess: () => false,
                loadNotificationsFailure: () => true,
            },
        ],
        // The list loads lazily when the tab mounts; without this flag the tab's first
        // render (before the load kicks off) would flash the empty state.
        notificationsLoaded: [
            false,
            {
                loadNotificationsSuccess: () => true,
                loadNotificationsFailure: () => true,
            },
        ],
    }),
    listeners(({ actions, values }) => {
        // Preserve the server total while the list is capped. Optimistic deletes can leave it
        // slightly stale until the next count reload, which is more accurate than replacing it with 500.
        const syncCountFromList = (notifications: HogFunctionType[]): void => {
            if (values.notificationsTruncated) {
                return
            }
            actions.loadNotificationCountSuccess(notifications.length)
        }

        return {
            // If a reload was already in flight when a mutation settled, that GET read pre-mutation
            // state and its pending-id tombstone is now cleared — reload once more so the stale
            // response can't revert a confirmed toggle or resurrect a confirmed delete.
            toggleNotificationEnabledSettled: () => {
                if (values.notificationsLoading) {
                    actions.loadNotifications()
                }
            },
            deleteNotificationSettled: () => {
                if (values.notificationsLoading) {
                    actions.loadNotifications()
                }
            },
            loadNotificationsSuccess: ({ notifications }) => syncCountFromList(notifications),
            setNotifications: ({ notifications }) => syncCountFromList(notifications),
            toggleNotificationEnabled: async ({ notificationId, enabled }) => {
                if (values.pendingToggleIds[notificationId]) {
                    return
                }

                const target = values.notifications.find((notification) => notification.id === notificationId)
                if (!target) {
                    return
                }
                actions.toggleNotificationEnabledStarted(notificationId)
                const previousEnabled = target.enabled

                const applyEnabled = (next: boolean): void => {
                    actions.setNotifications(
                        values.notifications.map((notification) =>
                            notification.id === notificationId ? { ...notification, enabled: next } : notification
                        )
                    )
                }

                applyEnabled(enabled)

                try {
                    const updatedNotification = await api.hogFunctions.update(notificationId, { enabled })
                    actions.setNotifications(
                        values.notifications.map((notification) =>
                            notification.id === notificationId ? updatedNotification : notification
                        )
                    )
                } catch (error) {
                    applyEnabled(previousEnabled)
                    lemonToast.error('Failed to update notification')
                    posthog.captureException(error, {
                        action: 'toggle-product-analytics-notification',
                        notification: notificationId,
                    })
                } finally {
                    actions.toggleNotificationEnabledSettled(notificationId)
                }
            },
            deleteNotification: async ({ notification }) => {
                actions.deleteNotificationStarted(notification.id)
                actions.setNotifications(values.notifications.filter((item) => item.id !== notification.id))

                let callbackFired = false
                await deleteWithUndo({
                    endpoint: `projects/${values.currentProjectId}/hog_functions`,
                    object: { id: notification.id, name: notification.name },
                    callback: (undo) => {
                        callbackFired = true
                        // Settle before reloading so the undone row isn't filtered back out
                        actions.deleteNotificationSettled(notification.id)
                        if (undo) {
                            actions.loadNotifications()
                        }
                    },
                })

                if (!callbackFired) {
                    actions.deleteNotificationSettled(notification.id)
                    actions.loadNotifications()
                }
            },
        }
    }),
    afterMount(({ actions }) => {
        actions.loadNotificationCount()
    }),
])