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.

33.3 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { decodeParams, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api, { ApiConfig, CountedPaginatedResponse } from 'lib/api'
import { TriggerExportProps } from 'lib/components/ExportButton/exporter'
import { convertPropertyGroupToProperties, isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
import { FEATURE_FLAGS, PERSON_DISPLAY_NAME_COLUMN_NAME } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { delay } from 'lib/utils/async'
import { objectsEqual } from 'lib/utils/objects'
import { isAbortedRequest } from 'lib/utils/requests'
import { toParams } from 'lib/utils/url'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { TODAY_PEOPLE_RECENT_KEY, TodayPeopleRecent } from '~/layout/today/todayPeople'
import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
import { DataTableNode, HogQLQuery, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
import {
    ActivityScope,
    AnyPropertyFilter,
    Breadcrumb,
    ExporterFormat,
    PersonListParams,
    PersonPropertyFilter,
    PersonType,
    PersonsTabType,
} from '~/types'
import type { TeamPublicType, TeamType } from '~/types'

import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from 'products/customer_analytics/frontend/constants'

import { personsCohortsRetrieve } from '../generated/api'
import type { CohortMinimalApi } from '../generated/api.schemas'
import {
    asDisplay,
    coercePropertyValue,
    getHogqlQueryStringForPersonId,
    parsePersonFromHogQLRow,
    pickBestPersonDistinctId,
} from '../person-utils'

function reportPersonPropertyUpdated(
    action: 'added' | 'updated' | 'removed',
    totalProperties: number,
    oldPropertyType?: string,
    newPropertyType?: string
): void {
    posthog.capture(`person property ${action}`, {
        old_property_type: oldPropertyType !== 'undefined' ? oldPropertyType : undefined,
        new_property_type: newPropertyType !== 'undefined' ? newPropertyType : undefined,
        total_properties: totalProperties,
    })
}

export interface PersonsLogicProps {
    cohort?: number | 'new'
    syncWithUrl?: boolean
    urlId?: string
    fixedProperties?: PersonPropertyFilter[]
}

export const PERSON_EVENTS_CONTEXT_KEY = 'person-profile-events'

function createInitialEventsPayload(personId: string): DataTableNode {
    return {
        kind: NodeKind.DataTableNode,
        full: true,
        showEventFilter: false,
        showEventsFilter: true,
        showTableViews: true,
        contextKey: PERSON_EVENTS_CONTEXT_KEY,
        hiddenColumns: [PERSON_DISPLAY_NAME_COLUMN_NAME],
        source: {
            kind: NodeKind.EventsQuery,
            select: defaultDataTableColumns(NodeKind.EventsQuery),
            personId: personId,
            after: '-24h',
        },
    }
}

function createInitialExceptionsPayload(personId: string): DataTableNode {
    return {
        kind: NodeKind.DataTableNode,
        full: true,
        showEventFilter: false,
        hiddenColumns: [PERSON_DISPLAY_NAME_COLUMN_NAME],
        source: {
            kind: NodeKind.EventsQuery,
            select: defaultDataTableColumns(NodeKind.EventsQuery),
            personId: personId,
            event: '$exception',
            after: '-24h',
        },
    }
}

function createInitialSurveyResponsesPayload(personId: string): DataTableNode {
    return {
        kind: NodeKind.DataTableNode,
        full: true,
        showEventFilter: false,
        hiddenColumns: [PERSON_DISPLAY_NAME_COLUMN_NAME],
        source: {
            kind: NodeKind.EventsQuery,
            select: ['*', 'properties.$survey_name', 'properties.$lib', 'timestamp'],
            personId: personId,
            event: 'survey sent',
            after: '-90d',
        },
    }
}

export function personViewedProperties(person: PersonType, postHogPropertyKeys: string[]): Record<string, unknown> {
    const keys = Object.keys(person.properties ?? {})
    const posthog_properties_count = keys.filter((key) => postHogPropertyKeys.includes(key)).length
    return {
        properties_count: keys.length,
        has_email: !!person.properties?.email,
        has_name: !!person.properties?.name,
        custom_properties_count: keys.length - posthog_properties_count,
        posthog_properties_count,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    activeTab: PersonsTabType | null
    apiDocsURL:
        | 'https://posthog.com/docs/api/cohorts#get-api-projects-project_id-cohorts-id-persons'
        | 'https://posthog.com/docs/api/persons'
    breadcrumbs: Breadcrumb[]
    cohortId: number | 'new' | undefined
    cohorts: CohortMinimalApi[] | null
    cohortsLoading: boolean
    currentTab: PersonsTabType
    defaultTab: PersonsTabType.PROFILE | PersonsTabType.PROPERTIES
    distinctId: string | null
    eventsQuery: DataTableNode | null
    eventsQueryIsDirty: boolean
    exceptionsQuery: DataTableNode | null
    exporterProps: TriggerExportProps[]
    feedEnabled: boolean
    hiddenListProperties: AnyPropertyFilter[]
    listFilters: PersonListParams
    person: PersonType | null
    personError: string | null
    personLoading: boolean
    persons: CountedPaginatedResponse<PersonType> & {
        offset: number
    }
    personsLoading: boolean
    primaryDistinctId: string | null
    sidePanelContext: SidePanelSceneContext
    splitMergeModalShown: boolean
    surveyResponsesQuery: DataTableNode | null
    todayPeopleRecent: TodayPeopleRecent | null
    urlId: any
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsLogicActions {
    deleteProperty: (key: string) => {
        key: string
    }
    editProperty: (
        key: string,
        newValue?: boolean | number | string | null
    ) => {
        key: string
        newValue: boolean | number | string | null | undefined
    }
    loadCohorts: () => any
    loadCohortsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCohortsSuccess: (
        cohorts: CohortMinimalApi[] | null,
        payload?: any
    ) => {
        cohorts: CohortMinimalApi[] | null
        payload?: any
    }
    loadPerson: (id: string) => {
        id: string
    }
    loadPersonFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPersonSuccess: (
        person: PersonType | null,
        payload?: {
            id: string
        }
    ) => {
        person: PersonType | null
        payload?: {
            id: string
        }
    }
    loadPersonUUID: (uuid: string) => {
        uuid: string
    }
    loadPersonUUIDFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPersonUUIDSuccess: (
        person: PersonType | null,
        payload?: {
            uuid: string
        }
    ) => {
        person: PersonType | null
        payload?: {
            uuid: string
        }
    }
    loadPersons: (url?: string | null) => {
        url: string | null
    }
    loadPersonsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPersonsSuccess: (
        persons: CountedPaginatedResponse<PersonType> & {
            offset: number
        },
        payload?: {
            url: string | null
        }
    ) => {
        persons: CountedPaginatedResponse<PersonType> & {
            offset: number
        }
        payload?: {
            url: string | null
        }
    }
    navigateToTab: (tab: PersonsTabType) => {
        tab: PersonsTabType
    }
    reportPersonDetailViewed: (person: PersonType) => {
        person: PersonType
    }
    resetEventsQuery: () => {
        value: true
    }
    setActiveTab: (tab: PersonsTabType) => {
        tab: PersonsTabType
    }
    setDistinctId: (distinctId: string) => {
        distinctId: string
    }
    setEventsQuery: (eventsQuery: DataTableNode | null) => {
        eventsQuery: DataTableNode | null
    }
    setExceptionsQuery: (exceptionsQuery: DataTableNode | null) => {
        exceptionsQuery: DataTableNode | null
    }
    setHiddenListProperties: (payload: AnyPropertyFilter[]) => {
        payload: AnyPropertyFilter[]
    }
    setListFilters: (payload: PersonListParams) => {
        payload: PersonListParams
    }
    setPerson: (person: PersonType | null) => {
        person: PersonType | null
    }
    setPersons: (persons: PersonType[]) => {
        persons: PersonType[]
    }
    setSplitMergeModalShown: (shown: boolean) => {
        shown: boolean
    }
    setSurveyResponsesQuery: (surveyResponsesQuery: DataTableNode | null) => {
        surveyResponsesQuery: DataTableNode | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        apiDocsURL: (
            arg: any
        ) =>
            | 'https://posthog.com/docs/api/cohorts#get-api-projects-project_id-cohorts-id-persons'
            | 'https://posthog.com/docs/api/persons'
        cohortId: (arg: any) => number | 'new' | undefined
        currentTab: (
            activeTab: PersonsTabType | null,
            defaultTab: PersonsTabType.PROFILE | PersonsTabType.PROPERTIES
        ) => PersonsTabType
        defaultTab: (feedEnabled: boolean) => PersonsTabType.PROFILE | PersonsTabType.PROPERTIES
        breadcrumbs: (
            person: PersonType | null,
            location: {
                hash: string
                pathname: string
                search: string
            },
            featureFlags: FeatureFlagsSet
        ) => Breadcrumb[]
        todayPeopleRecent: (person: PersonType | null) => TodayPeopleRecent | null
        sidePanelContext: (person: PersonType | null) => SidePanelSceneContext
        exporterProps: (listFilters: PersonListParams, arg: any) => TriggerExportProps[]
        urlId: (arg: any) => any
        feedEnabled: (featureFlags: FeatureFlagsSet) => boolean
        primaryDistinctId: (person: PersonType | null) => string | null
        eventsQueryIsDirty: (eventsQuery: DataTableNode | null, person: PersonType | null) => boolean
    }
}

export type personsLogicType = MakeLogicType<
    personsLogicValues,
    personsLogicActions,
    PersonsLogicProps,
    personsLogicMeta
>

export const personsLogic = kea<personsLogicType>([
    props({} as PersonsLogicProps),
    key((props) => {
        if (props.urlId) {
            return `url_${props.urlId}`
        }

        if (props.fixedProperties) {
            return JSON.stringify(props.fixedProperties)
        }

        if (props.cohort) {
            return `cohort_${props.cohort}`
        }

        return 'scene'
    }),
    path((key) => ['scenes', 'persons', 'personsLogic', key]),
    connect(() => ({
        values: [teamLogic, ['currentTeam'], featureFlagLogic, ['featureFlags']],
    })),
    actions({
        reportPersonDetailViewed: (person: PersonType) => ({ person }),
        setPerson: (person: PersonType | null) => ({ person }),
        setPersons: (persons: PersonType[]) => ({ persons }),
        loadPerson: (id: string) => ({ id }),
        loadPersonUUID: (uuid: string) => ({ uuid }),
        loadPersons: (url: string | null = '') => ({ url }),
        setListFilters: (payload: PersonListParams) => ({ payload }),
        setHiddenListProperties: (payload: AnyPropertyFilter[]) => ({ payload }),
        editProperty: (key: string, newValue?: string | number | boolean | null) => ({ key, newValue }),
        deleteProperty: (key: string) => ({ key }),
        navigateToTab: (tab: PersonsTabType) => ({ tab }),
        setActiveTab: (tab: PersonsTabType) => ({ tab }),
        setSplitMergeModalShown: (shown: boolean) => ({ shown }),
        setDistinctId: (distinctId: string) => ({ distinctId }),
        setEventsQuery: (eventsQuery: DataTableNode | null) => ({ eventsQuery }),
        setExceptionsQuery: (exceptionsQuery: DataTableNode | null) => ({ exceptionsQuery }),
        setSurveyResponsesQuery: (surveyResponsesQuery: DataTableNode | null) => ({ surveyResponsesQuery }),
        resetEventsQuery: true,
    }),
    loaders(({ values, actions, props }) => {
        const setupPersonQueries = (person: PersonType): void => {
            actions.reportPersonDetailViewed(person)
            if (person.id != null) {
                actions.setEventsQuery(createInitialEventsPayload(person.id))
                actions.setExceptionsQuery(createInitialExceptionsPayload(person.id))
                actions.setSurveyResponsesQuery(createInitialSurveyResponsesPayload(person.id))
            }
        }
        return {
            persons: [
                {
                    next: null,
                    previous: null,
                    count: 0,
                    results: [],
                    offset: 0,
                } as CountedPaginatedResponse<PersonType> & {
                    offset: number
                },
                {
                    loadPersons: async ({ url }) => {
                        let result: CountedPaginatedResponse<PersonType> & { offset: number }
                        if (!url) {
                            const newFilters: PersonListParams = { ...values.listFilters }
                            newFilters.properties = [
                                ...(values.listFilters.properties || []),
                                ...values.hiddenListProperties,
                            ]
                            newFilters.include_total = true // The total count is slow, but needed for infinite loading
                            if (props.cohort) {
                                result = {
                                    // This reads the cohorts API, whose generated client belongs to another product.
                                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use cohortsPersonsRetrieve() from 'products/cohorts/frontend/generated/api' instead.
                                    ...(await api.get(`api/cohort/${props.cohort}/persons/?${toParams(newFilters)}`)),
                                    offset: 0,
                                }
                            } else {
                                result = { ...(await api.persons.list(newFilters)), offset: 0 }
                            }
                        } else {
                            // The URL is the pagination link from the previous response.
                            // 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.
                            result = { ...(await api.get(url)), offset: parseInt(decodeParams(url).offset) || 0 }
                        }
                        return result
                    },
                },
            ],
            person: [
                null as PersonType | null,
                {
                    loadPerson: async ({ id }): Promise<PersonType | null> => {
                        const response = await api.persons.list({ distinct_id: id })
                        if (!response.results.length) {
                            return null
                        }
                        const person = response.results[0]
                        if (person) {
                            setupPersonQueries(person)
                        }

                        return person
                    },
                    loadPersonUUID: async ({ uuid }, breakpoint): Promise<PersonType | null> => {
                        let response: HogQLQueryResponse
                        try {
                            response = await api.query<HogQLQuery>(
                                {
                                    kind: NodeKind.HogQLQuery,
                                    query: getHogqlQueryStringForPersonId(),
                                    values: { id: uuid },
                                    tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
                                },
                                { refresh: 'blocking' }
                            )
                        } catch (error) {
                            // The blocking query is aborted when navigation moves on before it resolves.
                            // That's expected, not a load failure — drop the stale result instead of
                            // surfacing an error or letting it be captured as an exception. Emit a
                            // breadcrumb so the otherwise-silent swallow is still measurable.
                            if (isAbortedRequest(error)) {
                                posthog.capture('person_uuid_load_aborted')
                                breakpoint()
                                return values.person
                            }
                            throw error
                        }
                        const row = response?.results?.[0]
                        if (row) {
                            const person = parsePersonFromHogQLRow(row)
                            setupPersonQueries(person)
                            return person
                        }
                        return null
                    },
                },
            ],
            cohorts: [
                null as CohortMinimalApi[] | null,
                {
                    loadCohorts: async (): Promise<CohortMinimalApi[] | null> => {
                        if (!values.person?.id) {
                            return null
                        }
                        // projectId takes a team id here: the persons routes register on
                        // team_id even though OpenAPI renders the segment as {project_id}.
                        const response = await personsCohortsRetrieve(String(ApiConfig.getCurrentTeamId()), {
                            person_id: String(values.person.id),
                        })
                        return response.results
                    },
                },
            ],
        }
    }),
    reducers(() => ({
        listFilters: [
            {} as PersonListParams,
            {
                setListFilters: (state, { payload }) => {
                    const newFilters = { ...state, ...payload }

                    if (newFilters.properties?.length === 0) {
                        delete newFilters['properties']
                    }
                    if (newFilters.properties) {
                        newFilters.properties = convertPropertyGroupToProperties(
                            newFilters.properties.filter(isValidPropertyFilter)
                        )
                    }
                    return newFilters
                },
            },
        ],
        hiddenListProperties: [
            [] as AnyPropertyFilter[],
            {
                setHiddenListProperties: (state, { payload }) => {
                    let newProperties = [...state, ...payload]
                    if (newProperties) {
                        newProperties =
                            convertPropertyGroupToProperties(newProperties.filter(isValidPropertyFilter)) || []
                    }
                    return newProperties
                },
            },
        ],
        activeTab: [
            null as PersonsTabType | null,
            {
                navigateToTab: (_, { tab }) => tab,
                setActiveTab: (_, { tab }) => tab,
            },
        ],
        splitMergeModalShown: [
            false,
            {
                setSplitMergeModalShown: (_, { shown }) => shown,
            },
        ],
        persons: {
            setPerson: (state, { person }) => ({
                ...state,
                results: state.results.map((p) => (person && p.id === person.id ? person : p)),
            }),
            setPersons: (state, { persons }) => ({
                ...state,
                results: [...persons, ...state.results],
            }),
        },
        person: {
            loadPerson: () => null,
            setPerson: (_, { person }): PersonType | null => person,
        },
        personError: [
            null as string | null,
            {
                loadPerson: () => null,
                setPerson: () => null,
                loadPersonUUID: () => null,
                loadPersonFailure: (_, { error }) => error,
                loadPersonUUIDFailure: (_, { error }) => error,
            },
        ],
        distinctId: [
            null as string | null,
            {
                setDistinctId: (_, { distinctId }) => distinctId,
            },
        ],
        eventsQuery: [
            null as DataTableNode | null,
            {
                setEventsQuery: (_, { eventsQuery }) => {
                    return eventsQuery
                },
            },
        ],
        exceptionsQuery: [
            null as DataTableNode | null,
            {
                setExceptionsQuery: (_, { exceptionsQuery }) => exceptionsQuery,
            },
        ],
        surveyResponsesQuery: [
            null as DataTableNode | null,
            {
                setSurveyResponsesQuery: (_, { surveyResponsesQuery }) => surveyResponsesQuery,
            },
        ],
    })),
    selectors(() => ({
        apiDocsURL: [
            () => [(_, props) => props.cohort],
            (cohort: PersonsLogicProps['cohort']) =>
                cohort
                    ? 'https://posthog.com/docs/api/cohorts#get-api-projects-project_id-cohorts-id-persons'
                    : 'https://posthog.com/docs/api/persons',
        ],
        cohortId: [() => [(_, props) => props.cohort], (cohort: PersonsLogicProps['cohort']) => cohort],
        currentTab: [
            (s) => [s.activeTab, s.defaultTab],
            (activeTab: PersonsTabType | null, defaultTab: PersonsTabType.PROFILE | PersonsTabType.PROPERTIES) =>
                activeTab || defaultTab,
        ],
        defaultTab: [
            (s) => [s.feedEnabled],
            (feedEnabled: boolean) => (feedEnabled ? PersonsTabType.PROFILE : PersonsTabType.PROPERTIES),
        ],
        breadcrumbs: [
            (s) => [s.person, router.selectors.location, s.featureFlags],
            (
                person: PersonType | null,
                location: {
                    hash: string
                    pathname: string
                    search: string
                },
                featureFlags: FeatureFlagsSet
            ): Breadcrumb[] => {
                // The Today rail opens persons by UUID under `/persons/`.
                const personPath = featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV] ? /\/persons?\/.+/ : /\/person\/.+/
                const showPerson = person && location.pathname.match(personPath)
                const breadcrumbs: Breadcrumb[] = [
                    {
                        key: Scene.Persons,
                        name: 'Persons',
                        path: urls.persons(),
                        iconType: sceneConfigurations[Scene.Person].iconType || 'default_icon_type',
                    },
                ]
                if (showPerson) {
                    breadcrumbs.push({
                        key: [Scene.Person, person.id || 'unknown'],
                        name: asDisplay(person),
                        iconType: sceneConfigurations[Scene.Person].iconType || 'default_icon_type',
                    })
                }
                return breadcrumbs
            },
        ],

        [TODAY_PEOPLE_RECENT_KEY]: [
            (s) => [s.person],
            (person: PersonType | null): TodayPeopleRecent | null =>
                person?.id != null
                    ? { type: 'person', name: asDisplay(person), href: urls.personByUUID(String(person.id)) }
                    : null,
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            (s) => [s.person],
            (person: PersonType | null): SidePanelSceneContext => {
                return {
                    activity_scope: ActivityScope.PERSON,
                    // TODO: Is this correct? It doesn't seem to work...
                    activity_item_id: person?.id ? `${person?.id}` : undefined,
                }
            },
        ],

        exporterProps: [
            (s) => [s.listFilters, (_, { cohort }) => cohort],
            (listFilters: PersonListParams, cohort: number | 'new' | undefined): TriggerExportProps[] => [
                {
                    export_format: ExporterFormat.CSV,
                    export_context: {
                        path: cohort
                            ? api.cohorts.determineListUrl(cohort, listFilters)
                            : api.persons.determineListUrl(listFilters),
                    },
                },
            ],
        ],
        urlId: [() => [(_, props) => props.urlId], (urlId) => urlId],
        feedEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet) =>
                !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS],
        ],
        primaryDistinctId: [
            (s) => [s.person],
            (person: PersonType | null): string | null => pickBestPersonDistinctId(person?.distinct_ids) ?? null,
        ],
        eventsQueryIsDirty: [
            (s) => [s.eventsQuery, s.person],
            (eventsQuery: DataTableNode | null, person: PersonType | null): boolean => {
                if (!eventsQuery || !person?.id) {
                    return false
                }
                return !objectsEqual(eventsQuery, createInitialEventsPayload(person.id))
            },
        ],
    })),
    listeners(({ actions, values, cache }) => ({
        reportPersonDetailViewed: async ({ person }) => {
            // Not a kea breakpoint: kea cancels breakpoints when the logic unmounts, so a user who leaves the
            // page inside the delay would never be counted. The token keeps the debounce without that coupling.
            const token = Symbol('person viewed')
            cache.personViewedToken = token
            await delay(500)
            if (cache.personViewedToken !== token) {
                return
            }
            // Not a module-scope import: the taxonomy JSON is a quarter-MiB table, so load it only once a person is viewed.
            const { PROPERTY_KEYS } = await import('~/taxonomy/taxonomy')
            posthog.capture('person viewed', personViewedProperties(person, PROPERTY_KEYS))
        },
        resetEventsQuery: () => {
            const person = values.person
            if (person?.id != null) {
                actions.setEventsQuery(createInitialEventsPayload(person.id))
            }
        },
        editProperty: async ({ key, newValue }) => {
            const person = values.person

            if (person && person.id) {
                const parsedValue = coercePropertyValue(newValue ?? null)

                const oldPropertyType = person.properties[key] === null ? 'null' : typeof person.properties[key]
                const newPropertyType: string = parsedValue === null ? 'null' : typeof parsedValue
                const action: 'added' | 'updated' = Object.keys(person.properties).includes(key) ? 'updated' : 'added'

                const updatedProperties =
                    action === 'added'
                        ? { [key]: parsedValue, ...person.properties }
                        : { ...person.properties, [key]: parsedValue }

                actions.setPerson({ ...person, properties: updatedProperties })

                try {
                    await api.persons.updateProperty(person.id, key, parsedValue)
                    lemonToast.success(`Person property ${action}`)

                    reportPersonPropertyUpdated(
                        action,
                        Object.keys(updatedProperties).length,
                        oldPropertyType,
                        newPropertyType
                    )
                } catch {
                    actions.setPerson({ ...person })
                    lemonToast.error(`Failed to update person property`)
                }
            }
        },
        deleteProperty: async ({ key }) => {
            const person = values.person

            if (person && person.id) {
                const { [key]: _, ...updatedProperties } = person.properties

                actions.setPerson({ ...person, properties: updatedProperties })

                try {
                    await api.persons.deleteProperty(person.id, key)
                    lemonToast.success(`Person property deleted`)

                    reportPersonPropertyUpdated('removed', 1, undefined, undefined)
                } catch {
                    actions.setPerson({ ...person })
                    lemonToast.error(`Failed to delete person property`)
                }
            }
        },
    })),
    trackedActionToUrl(({ values, props }) => ({
        setListFilters: () => {
            if (props.syncWithUrl && router.values.location.pathname.indexOf('/persons') > -1) {
                return ['/persons', values.listFilters, undefined, { replace: true }]
            }
        },
        navigateToTab: () => {
            if (
                props.syncWithUrl &&
                router.values.location.pathname.indexOf('/person') > -1 &&
                router.values.hashParams.activeTab !== values.activeTab
            ) {
                // When navigating away from recordings tab, clear sessionRecordingId from search params
                // to prevent urlToAction from forcing back to recordings tab
                let searchParams = router.values.searchParams
                if (values.activeTab !== PersonsTabType.SESSION_RECORDINGS && searchParams.sessionRecordingId) {
                    const { sessionRecordingId: _, ...restSearchParams } = searchParams
                    searchParams = restSearchParams
                }
                return [
                    router.values.location.pathname,
                    searchParams,
                    {
                        ...router.values.hashParams,
                        activeTab: values.activeTab,
                    },
                ]
            }
        },
    })),
    urlToAction(({ actions, values, props }) => ({
        '/person/*': ({ _: rawPersonDistinctId }, { sessionRecordingId }, { activeTab }) => {
            if (props.syncWithUrl) {
                if (sessionRecordingId && values.activeTab !== PersonsTabType.SESSION_RECORDINGS) {
                    actions.navigateToTab(PersonsTabType.SESSION_RECORDINGS)
                } else if (activeTab && values.activeTab !== activeTab) {
                    actions.navigateToTab(activeTab as PersonsTabType)
                }

                if (!activeTab && values.activeTab !== values.defaultTab) {
                    actions.setActiveTab(values.defaultTab)
                }

                if (rawPersonDistinctId) {
                    // Decode the personDistinctId because it's coming from the URL, and it could be an email which gets encoded
                    const decodedPersonDistinctId = decodeURIComponent(rawPersonDistinctId)

                    if (!values.person || !values.person.distinct_ids.includes(decodedPersonDistinctId)) {
                        actions.loadPerson(decodedPersonDistinctId) // underscore contains the wildcard
                    }
                }
            }
        },
        '/persons/*': ({ _: rawPersonUUID }, { sessionRecordingId }, { activeTab }) => {
            if (props.syncWithUrl) {
                if (sessionRecordingId && values.activeTab !== PersonsTabType.SESSION_RECORDINGS) {
                    actions.navigateToTab(PersonsTabType.SESSION_RECORDINGS)
                } else if (activeTab && values.activeTab !== activeTab) {
                    actions.navigateToTab(activeTab as PersonsTabType)
                }

                if (!activeTab) {
                    actions.setActiveTab(values.defaultTab)
                }

                if (rawPersonUUID) {
                    const decodedPersonUUID = decodeURIComponent(rawPersonUUID)
                    if (!values.person || values.person.id != decodedPersonUUID) {
                        actions.loadPersonUUID(decodedPersonUUID)
                    }
                }
            }
        },
    })),
    events(({ props, actions }) => ({
        afterMount: () => {
            if (props.cohort && typeof props.cohort === 'number') {
                actions.setListFilters({ cohort: props.cohort })
                actions.loadPersons()
            }

            if (props.fixedProperties) {
                actions.setHiddenListProperties(props.fixedProperties)
                actions.loadPersons()
            }
        },
    })),
])