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.

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

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

import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'

import {
    webAnalyticsPathCleaningSuggestionsApply,
    webAnalyticsPathCleaningSuggestionsPreview,
} from 'products/web_analytics/frontend/generated/api'
import type {
    PathCleaningSuggestionIssueApi,
    PreviewPathCleaningSuggestionResponseApi,
} from 'products/web_analytics/frontend/generated/api.schemas'

export const PATH_CLEANING_SUGGESTIONS_KIND = 'path_cleaning_suggestions'

interface HealthIssueRecord {
    id: string
    created_at: string
    payload: Record<string, any>
}

const toSuggestion = (issue: HealthIssueRecord): PathCleaningSuggestionIssueApi => ({
    id: issue.id,
    created_at: issue.created_at,
    rules: issue.payload?.rules ?? [],
    model: issue.payload?.model ?? '',
    sampled_path_count: issue.payload?.sampled_path_count ?? 0,
    distinct_path_count: issue.payload?.distinct_path_count ?? 0,
})

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pathCleaningSuggestionsLogicValues {
    currentTeamId: number | null // teamLogic
    applying: boolean
    handledIds: string[]
    latestSuggestion: PathCleaningSuggestionIssueApi | null
    preview: PreviewPathCleaningSuggestionResponseApi | null
    previewLoading: boolean
    previewOpen: boolean
    suggestions: PathCleaningSuggestionIssueApi[]
    suggestionsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pathCleaningSuggestionsLogicActions {
    loadCurrentTeam: () => any // teamLogic
    applySuggestion: (id: string) => {
        id: string
    }
    applySuggestionFinished: () => {
        value: true
    }
    closePreview: () => {
        value: true
    }
    closePreviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    closePreviewSuccess: (
        preview: null,
        payload?: {
            value: true
        }
    ) => {
        preview: null
        payload?: {
            value: true
        }
    }
    dismissSuggestion: (id: string) => {
        id: string
    }
    loadPreview: ({ id }: { id: string }) => {
        id: string
    }
    loadPreviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPreviewSuccess: (
        preview: PreviewPathCleaningSuggestionResponseApi | null,
        payload?: {
            id: string
        }
    ) => {
        preview: PreviewPathCleaningSuggestionResponseApi | null
        payload?: {
            id: string
        }
    }
    loadSuggestions: () => any
    loadSuggestionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSuggestionsSuccess: (
        suggestions: PathCleaningSuggestionIssueApi[],
        payload?: any
    ) => {
        suggestions: PathCleaningSuggestionIssueApi[]
        payload?: any
    }
    openPreview: (id: string) => {
        id: string
    }
    resetForTeamChange: () => {
        value: true
    }
    resetForTeamChangeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    resetForTeamChangeSuccess: (
        preview: null,
        payload?: {
            value: true
        }
    ) => {
        preview: null
        payload?: {
            value: true
        }
    }
    unhandleSuggestion: (id: string) => {
        id: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pathCleaningSuggestionsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        latestSuggestion: (
            suggestions: PathCleaningSuggestionIssueApi[],
            handledIds: string[]
        ) => PathCleaningSuggestionIssueApi | null
    }
}

export type pathCleaningSuggestionsLogicType = MakeLogicType<
    pathCleaningSuggestionsLogicValues,
    pathCleaningSuggestionsLogicActions,
    Record<string, any>,
    pathCleaningSuggestionsLogicMeta
>

export const pathCleaningSuggestionsLogic = kea<pathCleaningSuggestionsLogicType>([
    path(['scenes', 'settings', 'environment', 'pathCleaningSuggestionsLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId']],
        actions: [teamLogic, ['loadCurrentTeam']],
    })),
    actions({
        applySuggestion: (id: string) => ({ id }),
        dismissSuggestion: (id: string) => ({ id }),
        unhandleSuggestion: (id: string) => ({ id }),
        openPreview: (id: string) => ({ id }),
        closePreview: true,
        resetForTeamChange: true,
        applySuggestionFinished: true,
    }),
    loaders(({ values }) => ({
        preview: [
            null as PreviewPathCleaningSuggestionResponseApi | null,
            {
                loadPreview: async ({ id }: { id: string }) => {
                    if (!values.currentTeamId) {
                        return null
                    }
                    return await webAnalyticsPathCleaningSuggestionsPreview(String(values.currentTeamId), id)
                },
                closePreview: () => null,
                resetForTeamChange: () => null,
            },
        ],
        suggestions: [
            [] as PathCleaningSuggestionIssueApi[],
            {
                loadSuggestions: async () => {
                    if (!values.currentTeamId) {
                        return []
                    }
                    // Suggestions are stored as health issues; the newest active, non-dismissed one is
                    // the actionable suggestion.
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    const response = await api.get<{ results: HealthIssueRecord[] }>(
                        `api/projects/${values.currentTeamId}/health_issues/?kind=${PATH_CLEANING_SUGGESTIONS_KIND}&status=active&dismissed=false`
                    )
                    return response.results.map(toSuggestion)
                },
                resetForTeamChange: () => [],
            },
        ],
    })),
    reducers({
        // Optimistically hide a suggestion the moment it's applied or dismissed.
        handledIds: [
            [] as string[],
            {
                applySuggestion: (state, { id }) => [...state, id],
                dismissSuggestion: (state, { id }) => [...state, id],
                unhandleSuggestion: (state, { id }) => state.filter((handledId) => handledId !== id),
                resetForTeamChange: () => [],
            },
        ],
        // In-flight guard: both Apply buttons disable while the POST is running.
        applying: [
            false,
            {
                applySuggestion: () => true,
                applySuggestionFinished: () => false,
                resetForTeamChange: () => false,
            },
        ],
        previewOpen: [
            false,
            {
                openPreview: () => true,
                closePreview: () => false,
                // Applying or dismissing from the modal is a terminal action for the suggestion.
                applySuggestion: () => false,
                dismissSuggestion: () => false,
                resetForTeamChange: () => false,
            },
        ],
    }),
    selectors({
        latestSuggestion: [
            (s) => [s.suggestions, s.handledIds],
            (
                suggestions: PathCleaningSuggestionIssueApi[],
                handledIds: string[]
            ): PathCleaningSuggestionIssueApi | null =>
                suggestions.find((suggestion) => !handledIds.includes(suggestion.id)) ?? null,
        ],
    }),
    listeners(({ values, actions }) => ({
        openPreview: async ({ id }) => {
            actions.loadPreview({ id })
        },
        loadPreviewFailure: () => {
            actions.closePreview()
            lemonToast.error('Could not load the preview. Please try again.')
        },
        applySuggestion: async ({ id }) => {
            if (!values.currentTeamId) {
                actions.applySuggestionFinished()
                return
            }
            try {
                const result = await webAnalyticsPathCleaningSuggestionsApply(String(values.currentTeamId), id)
                lemonToast.success(`Applied ${result.applied} path cleaning rule${result.applied === 1 ? '' : 's'}`)
                // Refresh the team so the rules table reflects the merged path_cleaning_filters.
                actions.loadCurrentTeam()
            } catch {
                // Roll back the optimistic hide and tell the user, so nothing is silently lost.
                actions.unhandleSuggestion(id)
                lemonToast.error('Could not apply the path cleaning suggestions. Please try again.')
            } finally {
                actions.applySuggestionFinished()
            }
        },
        dismissSuggestion: async ({ id }) => {
            if (!values.currentTeamId) {
                return
            }
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                await api.update(`api/projects/${values.currentTeamId}/health_issues/${id}/`, { dismissed: true })
            } catch {
                actions.unhandleSuggestion(id)
                lemonToast.error('Could not dismiss the suggestion. Please try again.')
            }
        },
    })),
    subscriptions(({ actions }) => ({
        // The logic outlives project switches; a team change must drop the previous
        // project's suggestion state so preview/apply can't target a stale issue id.
        currentTeamId: (teamId: number | null, oldTeamId: number | null | undefined) => {
            if (oldTeamId !== undefined && teamId !== oldTeamId) {
                actions.resetForTeamChange()
                if (teamId) {
                    actions.loadSuggestions()
                }
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadSuggestions()
    }),
])