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.

26.7 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    connect,
    kea,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { combineUrl, urlToAction } from 'kea-router'

import api from 'lib/api'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { assignField, isGroupType, isSessionType } from 'lib/utils/guards'
import { cohortSavedToast } from 'scenes/cohorts/cohortSavedToast'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { cohortsModel } from '~/models/cohortsModel'
import { groupsModel } from '~/models/groupsModel'
import { extractValidationError } from '~/queries/nodes/InsightViz/utils'
import { performQuery } from '~/queries/query'
import { setLatestVersionsOnQuery } from '~/queries/schema/query-versions'
import {
    ActorsQuery,
    DataTableNode,
    ExperimentActorsQuery,
    FunnelsActorsQuery,
    InsightActorsQuery,
    InsightActorsQueryOptions,
    InsightActorsQueryOptionsResponse,
    NodeKind,
    PathsV2ActorsQuery,
    TrendsQuery,
    insightActorsQueryOptionsResponseKeys,
} from '~/queries/schema/schema-general'
import {
    ActivityTab,
    ActorType,
    CommonActorType,
    GroupActorType,
    PersonActorType,
    SessionActorType,
    RecordingUniversalFilters,
} from '~/types'

import type { Noun } from '../../../models/groupsModel'
import type { InsightQueryNode } from '../../../queries/schema/schema-general'
import type { GroupType, GroupTypeIndex } from '../../../types'
import { getPersonsRecordingFilters } from './getPersonsRecordingFilters'

const RESULTS_PER_PAGE = 100

export interface PersonModalLogicProps {
    query?: InsightActorsQuery | FunnelsActorsQuery | ExperimentActorsQuery | PathsV2ActorsQuery | null
    url?: string | null
    additionalSelect?: Partial<Record<keyof CommonActorType, string>>
    orderBy?: string[]
}

export interface ListActorsResponse {
    results: {
        count: number
        people: ActorType[]
    }[]
    missing_persons?: number
    next?: string
    offset?: number // Offset for HogQL queries
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsModalLogicValues {
    aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
    groupTypes: Map<GroupTypeIndex, GroupType> // groupsModel
    currentTeamId: number | null // teamLogic
    actorLabel: Noun
    actors: ActorType[]
    actorsQuery: ActorsQuery | null
    actorsResponse: ListActorsResponse | null
    actorsResponseLoading: boolean
    errorObject: Record<string, any> | null
    exploreUrl: string | null
    insightActorsQueryOptions: InsightActorsQueryOptionsResponse | null
    insightActorsQueryOptionsLoading: boolean
    insightEventsQueryUrl: string | null
    isCohortModalOpen: boolean
    isModalOpen: boolean
    missingActorsCount: number
    propertiesTimelineQuery: InsightActorsQuery | null
    query: FunnelsActorsQuery | InsightActorsQuery | null
    recordingFilters: Partial<RecordingUniversalFilters>
    searchTerm: string
    selectFields: string[]
    sessionIdsFromLoadedActors: string[]
    validationError: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsModalLogicActions {
    reportPersonsModalSearched: (params: { actorType?: string; teamId?: number | null }) => {
        params: {
            actorType?: string | undefined
            teamId?: number | null | undefined
        }
    } // eventUsageLogic
    reportPersonsModalViewed: (params: any) => {
        params: any
    } // eventUsageLogic
    closeModal: () => boolean
    loadActors: ({ url, clear, offset }: { clear?: boolean; offset?: number; url?: string | null }) => {
        clear: boolean | undefined
        offset: number | undefined
        url: string | null | undefined
    }
    loadActorsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadActorsQueryOptions: (query: FunnelsActorsQuery | InsightActorsQuery) => {
        query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode>
    }
    loadActorsQueryOptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadActorsQueryOptionsSuccess: (
        insightActorsQueryOptions:
            | InsightActorsQueryOptionsResponse
            | {
                  [k: string]: any
              }
            | null,
        payload?: {
            query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode>
        }
    ) => {
        insightActorsQueryOptions:
            | InsightActorsQueryOptionsResponse
            | {
                  [k: string]: any
              }
            | null
        payload?: {
            query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode>
        }
    }
    loadActorsSuccess: (
        actorsResponse: ListActorsResponse | null,
        payload?: {
            clear: boolean | undefined
            offset: number | undefined
            url: string | null | undefined
        }
    ) => {
        actorsResponse: ListActorsResponse | null
        payload?: {
            clear: boolean | undefined
            offset: number | undefined
            url: string | null | undefined
        }
    }
    loadNextActors: () => {
        value: true
    }
    resetActors: () => boolean
    saveAsCohort: (cohortName: string) => {
        cohortName: string
    }
    setIsCohortModalOpen: (isOpen: boolean) => {
        isOpen: boolean
    }
    setSearchTerm: (search: string) => {
        search: string
    }
    updateActorsQuery: (query: Partial<InsightActorsQuery> | Partial<FunnelsActorsQuery>) => {
        query: Partial<InsightActorsQuery<InsightQueryNode>> | Partial<FunnelsActorsQuery>
    }
    updateQuery: (query: FunnelsActorsQuery | InsightActorsQuery) => {
        query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsModalLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        actorLabel: (
            actors: ActorType[],
            aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
        ) => Noun
        validationError: (errorObject: Record<string, any> | null) => string | null
        selectFields: (arg: any) => string[]
        actorsQuery: (
            arg: any,
            query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode> | null,
            searchTerm: string,
            selectFields: string[]
        ) => ActorsQuery | null
        exploreUrl: (actorsQuery: ActorsQuery | null) => string | null
        insightEventsQueryUrl: (actorsQuery: ActorsQuery | null) => string | null
        propertiesTimelineQuery: (
            query: FunnelsActorsQuery | InsightActorsQuery<InsightQueryNode> | null
        ) => InsightActorsQuery | null
        sessionIdsFromLoadedActors: (actors: ActorType[]) => string[]
        recordingFilters: (
            actorsQuery: ActorsQuery | null,
            sessionIdsFromLoadedActors: string[]
        ) => Partial<RecordingUniversalFilters>
    }
}

export type personsModalLogicType = MakeLogicType<
    personsModalLogicValues,
    personsModalLogicActions,
    PersonModalLogicProps,
    personsModalLogicMeta
>

export const personsModalLogic = kea<personsModalLogicType>([
    path(['scenes', 'trends', 'personsModalLogic']),
    props({} as PersonModalLogicProps),
    actions({
        setSearchTerm: (search: string) => ({ search }),
        saveAsCohort: (cohortName: string) => ({ cohortName }),
        resetActors: () => true,
        closeModal: () => true,
        setIsCohortModalOpen: (isOpen: boolean) => ({ isOpen }),
        loadActors: ({ url, clear, offset }: { url?: string | null; clear?: boolean; offset?: number }) => ({
            url,
            clear,
            offset,
        }),
        loadNextActors: true,
        updateQuery: (query: InsightActorsQuery | FunnelsActorsQuery) => ({ query }),
        updateActorsQuery: (query: Partial<InsightActorsQuery> | Partial<FunnelsActorsQuery>) => ({ query }),
        loadActorsQueryOptions: (query: InsightActorsQuery | FunnelsActorsQuery) => ({ query }),
    }),
    connect(() => ({
        values: [groupsModel, ['groupTypes', 'aggregationLabel'], teamLogic, ['currentTeamId']],
        actions: [eventUsageLogic, ['reportPersonsModalViewed', 'reportPersonsModalSearched']],
    })),

    loaders(({ values, actions, props }) => ({
        actorsResponse: [
            null as ListActorsResponse | null,
            {
                loadActors: async ({ url, clear, offset }, breakpoint) => {
                    if (url) {
                        url += '&include_recordings=true'

                        if (values.searchTerm) {
                            url += `&search=${values.searchTerm}`
                        }
                    }
                    if (url && !values.actorsQuery) {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                        const res = await api.get(url)
                        breakpoint()

                        if (clear) {
                            actions.resetActors()
                        }
                        return res
                    }
                    if (values.actorsQuery) {
                        const response = await performQuery(
                            setLatestVersionsOnQuery(
                                {
                                    ...values.actorsQuery,
                                    limit: offset ? offset * 2 : RESULTS_PER_PAGE,
                                    offset,
                                },
                                { recursion: false }
                            ) as ActorsQuery
                        )
                        breakpoint()

                        const assembledSelectFields = values.selectFields
                        const fieldKeys = Object.keys(props.additionalSelect || {}) as Array<keyof CommonActorType>
                        const fieldValues = Object.values(props.additionalSelect || {}) as Array<keyof CommonActorType>
                        const additionalFieldIndices = fieldValues.map((field) => assembledSelectFields.indexOf(field))
                        const personColumnIndex = (response.columns || []).indexOf('person')
                        const newResponse: ListActorsResponse = {
                            results: [
                                {
                                    count: response.results.length,
                                    people: response.results.map((result): ActorType => {
                                        if (result[0].group_type_index !== undefined) {
                                            const group: GroupActorType = {
                                                type: 'group',
                                                id: result[0].id,
                                                group_key: result[0].group_key,
                                                group_type_index: result[0].group_type_index,
                                                properties: result[0].group_properties,
                                                created_at: result[0].created_at,
                                                matched_recordings: [],
                                                value_at_data_point: null,
                                            }
                                            fieldKeys.forEach((field, index) => {
                                                assignField(group, field, result[additionalFieldIndices[index]])
                                            })
                                            return group
                                        }

                                        if (result[0].session_id !== undefined) {
                                            const session: SessionActorType = {
                                                type: 'session',
                                                id: result[0].session_id,
                                                properties: result[0],
                                                created_at: result[0].$start_timestamp,
                                                matched_recordings: [],
                                                value_at_data_point: null,
                                                person: personColumnIndex >= 0 ? result[personColumnIndex] : undefined,
                                            }
                                            fieldKeys.forEach((field, index) => {
                                                assignField(session, field, result[additionalFieldIndices[index]])
                                            })
                                            return session
                                        }
                                        const person: PersonActorType = {
                                            type: 'person',
                                            id: result[0].id,
                                            distinct_ids: result[0].distinct_ids,
                                            is_identified: result[0].is_identified,
                                            properties: result[0].properties,
                                            created_at: result[0].created_at,
                                            matched_recordings: [],
                                            value_at_data_point: null,
                                        }
                                        fieldKeys.forEach((field, index) => {
                                            assignField(person, field, result[additionalFieldIndices[index]])
                                        })
                                        return person
                                    }),
                                },
                            ],
                        }
                        newResponse.offset = response.hasMore ? response.offset + response.limit : undefined
                        newResponse.missing_persons = response.missing_actors_count
                        if (clear) {
                            actions.resetActors()
                        }
                        return newResponse
                    }
                    return null
                },
            },
        ],
        insightActorsQueryOptions: [
            null as InsightActorsQueryOptionsResponse | null,
            {
                loadActorsQueryOptions: async ({ query }) => {
                    if (!query) {
                        return values.insightActorsQueryOptions || null
                    }
                    const optionsQuery: InsightActorsQueryOptions = setLatestVersionsOnQuery(
                        {
                            kind: NodeKind.InsightActorsQueryOptions,
                            source: query,
                        },
                        { recursion: false }
                    )
                    const response = await performQuery(optionsQuery, {}, 'blocking')

                    return Object.fromEntries(
                        Object.entries(response).filter(([key, _]) =>
                            insightActorsQueryOptionsResponseKeys.includes(key)
                        )
                    )
                },
            },
        ],
    })),

    reducers(({ props }) => ({
        query: [
            props.query as InsightActorsQuery | FunnelsActorsQuery | null,
            {
                updateQuery: (_, { query }) => query,
            },
        ],
        actors: [
            [] as ActorType[],
            {
                loadActorsSuccess: (state, { actorsResponse }) => [
                    ...state,
                    ...(actorsResponse?.results?.[0]?.people || []),
                ],
                resetActors: () => [],
            },
        ],
        errorObject: [
            null as Record<string, any> | null,
            {
                loadActors: () => null,
                loadActorsFailure: (_, { errorObject }) => errorObject,
                loadActorsSuccess: () => null,
            },
        ],
        missingActorsCount: [
            0,
            {
                loadActorsSuccess: (state, { actorsResponse }) => state + (actorsResponse?.missing_persons || 0),
                resetActors: () => 0,
            },
        ],
        searchTerm: [
            '',
            {
                setSearchTerm: (_, { search }) => search,
            },
        ],
        isModalOpen: [
            true,
            {
                closeModal: () => false,
            },
        ],
        isCohortModalOpen: [
            false,
            {
                setIsCohortModalOpen: (_, { isOpen }) => isOpen,
                closeModal: () => false,
            },
        ],
    })),

    listeners(({ actions, values, props }) => ({
        setSearchTerm: async ({ search }, breakpoint) => {
            await breakpoint(500)
            actions.loadActors({ url: props.url, clear: true })

            if (search) {
                actions.reportPersonsModalSearched({
                    teamId: values.currentTeamId,
                    actorType: values.actorLabel.singular,
                })
            }
        },
        saveAsCohort: async ({ cohortName }) => {
            const cohortParams = {
                is_static: true,
                name: cohortName,
            }
            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use cohortsCreate() from 'products/cohorts/frontend/generated/api' instead.
            const cohort = await api.create('api/cohort', { ...cohortParams, query: values.actorsQuery })
            cohortsModel.actions.cohortCreated(cohort)
            cohortSavedToast(cohort, 'persons_modal', `cohort-saved-${cohort.id}`)
            actions.setIsCohortModalOpen(false)
        },
        loadNextActors: () => {
            if (values.actorsResponse?.next) {
                actions.loadActors({ url: values.actorsResponse.next })
            }
            if (values.actorsResponse?.offset) {
                actions.loadActors({ offset: values.actorsResponse.offset })
            }
        },
        loadActors: () => {
            if (values.query && !values.insightActorsQueryOptions) {
                actions.loadActorsQueryOptions(values.query)
            }
        },
        updateActorsQuery: ({ query: q }) => {
            if (q && values.query) {
                // The partial always targets the current query's kind; the spread can't express that.
                actions.updateQuery({ ...values.query, ...q } as InsightActorsQuery | FunnelsActorsQuery)
                actions.loadActors({ offset: 0, clear: true })
            }
        },
    })),

    selectors({
        actorLabel: [
            (s) => [s.actors, s.aggregationLabel],
            (
                actors: ActorType[],
                aggregationLabel: (
                    groupTypeIndex: number | null | undefined,
                    deferToUserWording?: boolean
                ) => import('~/models/groupsModel').Noun
            ) => {
                const firstResult = actors[0]

                if (!firstResult) {
                    return { singular: 'result', plural: 'results' }
                }
                if (isSessionType(firstResult)) {
                    return { singular: 'session', plural: 'sessions' }
                }
                return aggregationLabel(isGroupType(firstResult) ? firstResult.group_type_index : undefined)
            },
        ],
        validationError: [
            (s) => [s.errorObject],
            (errorObject: Record<string, any> | null): string | null => {
                return extractValidationError(errorObject)
            },
        ],
        selectFields: [
            () => [(_, p) => p.additionalSelect],
            (additionalSelect: PersonModalLogicProps['additionalSelect']): string[] => {
                const extra = Object.values(additionalSelect || {})
                return ['actor', ...extra]
            },
        ],
        actorsQuery: [
            (s) => [(_, p) => p.orderBy, s.query, s.searchTerm, s.selectFields],
            (
                orderBy,
                query: FunnelsActorsQuery | InsightActorsQuery | null,
                searchTerm: string,
                selectFields: string[]
            ): ActorsQuery | null => {
                if (!query) {
                    return null
                }
                const sourceTags = { ...query.source?.tags, ...query.tags }
                const activeScene = sceneLogic.findMounted()?.values.activeSceneId
                const tags = {
                    ...sourceTags,
                    ...(activeScene && !sourceTags.scene ? { scene: activeScene } : {}),
                }
                return setLatestVersionsOnQuery(
                    {
                        kind: NodeKind.ActorsQuery,
                        source: query,
                        select: selectFields,
                        orderBy: orderBy || [],
                        search: searchTerm,
                        ...(Object.keys(tags).length > 0 ? { tags } : {}),
                    },
                    { recursion: false }
                )
            },
        ],
        exploreUrl: [
            (s) => [s.actorsQuery],
            (actorsQuery: ActorsQuery | null): string | null => {
                if (!actorsQuery) {
                    return null
                }
                const { select: _select, ...source } = actorsQuery
                const query: DataTableNode = {
                    kind: NodeKind.DataTableNode,
                    source,
                    full: true,
                }
                return urls.insightNew({ query })
            },
        ],
        insightEventsQueryUrl: [
            (s) => [s.actorsQuery],
            (actorsQuery: ActorsQuery): string | null => {
                if (!actorsQuery) {
                    return null
                }

                const { select: _select, ...source } = actorsQuery

                const kind =
                    actorsQuery.source && 'source' in actorsQuery.source ? actorsQuery.source.source?.kind : null

                if (!kind || ![NodeKind.TrendsQuery].includes(kind)) {
                    return null
                }

                const { includeRecordings, ...insightActorsQuery } = source.source as InsightActorsQuery

                const trendsQuery = insightActorsQuery.source as TrendsQuery
                const seriesIndex = insightActorsQuery.series ?? 0
                const seriesNode = trendsQuery.series?.[seriesIndex]
                const eventName = seriesNode && 'event' in seriesNode ? seriesNode.event : undefined

                const query: DataTableNode = {
                    kind: NodeKind.DataTableNode,
                    source: {
                        kind: NodeKind.EventsQuery,
                        source: insightActorsQuery,
                        select: ['*', 'event', 'person', 'timestamp'],
                        // Show all events by default because date range is filtered by the source
                        after: 'all',
                        event: eventName,
                    },
                    full: true,
                }

                // Route to the dedicated events explorer rather than /insights/new. The explorer reads the
                // query synchronously from the `#q=` hash and renders the events table directly, whereas the
                // insight scene round-trips this drill-down through an async query upgrade that can drop it and
                // fall back to a default Trends insight.
                return combineUrl(urls.activity(ActivityTab.ExploreEvents), {}, { q: query }).url
            },
        ],
        propertiesTimelineQuery: [
            (s) => [s.query],
            (query: FunnelsActorsQuery | InsightActorsQuery | null): InsightActorsQuery | null => {
                // The backend supports Trends data points of events or actions series. Stickiness, funnel and path
                // data points have no single time window, and a dormant lifecycle actor has no events in its window.
                if (query?.kind !== NodeKind.InsightActorsQuery || query.source.kind !== NodeKind.TrendsQuery) {
                    return null
                }
                const series = query.source.series[query.series ?? 0]
                return series?.kind === NodeKind.EventsNode || series?.kind === NodeKind.ActionsNode ? query : null
            },
        ],
        sessionIdsFromLoadedActors: [
            (s) => [s.actors],
            (actors: ActorType[]): string[] => {
                // Extract all session IDs from loaded actors' matched_recordings
                const sessionIds: string[] = []
                actors.forEach((actor: ActorType) => {
                    if (actor.matched_recordings) {
                        actor.matched_recordings.forEach((recording) => {
                            if (recording.session_id) {
                                sessionIds.push(recording.session_id)
                            }
                        })
                    }
                })
                return sessionIds
            },
        ],
        recordingFilters: [
            (s) => [s.actorsQuery, s.sessionIdsFromLoadedActors],
            (actorsQuery: ActorsQuery | null, sessionIds: string[]): Partial<RecordingUniversalFilters> =>
                getPersonsRecordingFilters(actorsQuery, sessionIds),
        ],
    }),

    afterMount(({ actions, props }) => {
        actions.loadActors({ url: props.url })

        actions.reportPersonsModalViewed({
            url: props.url,
            query: props.query,
        })
    }),

    urlToAction(({ cache, actions }) => ({
        '*': (_a, _b, _c, { pathname }) => {
            if (!cache['lastPathname']) {
                cache['lastPathname'] = pathname
                return
            }
            // If we click anything that navigates us away, close the modal but
            // allowing for changes in hash due to the SessionsRecordings Modal
            if (cache['lastPathname'] !== pathname) {
                actions.closeModal()
            }
        },
    })),

    propsChanged(({ props, actions }, oldProps) => {
        if (props.url !== oldProps.url) {
            actions.loadActors({ url: props.url, clear: true })
        }
    }),
])