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.

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

import api from 'lib/api'
import type { CountedPaginatedResponse } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'

import { PersonType } from '~/types'
import type { PersonListParams } from '~/types'

import { personsLogic } from './personsLogic'

export interface SplitPersonLogicProps {
    person: PersonType
    urlId: string
}

export type PersonUuids = NonNullable<PersonType['uuid']>[]

export type SplitMode = 'all' | 'partial'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mergeSplitPersonLogicValues {
    persons: CountedPaginatedResponse<PersonType> & {
        offset: number
    } // personsLogic
    distinctIdsToSplit: string[]
    executed: boolean
    executedLoading: boolean
    person: PersonType
    selectedPersonToAssignSplit: string | null
    splitMode: SplitMode
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mergeSplitPersonLogicActions {
    loadPersons: (url?: string | null | undefined) => {
        url: string | null
    } // personsLogic
    setListFilters: (payload: PersonListParams) => {
        payload: PersonListParams
    } // personsLogic
    setPerson: (person: PersonType | null) => {
        person: PersonType | null
    } // personsLogic
    setSplitMergeModalShown: (shown: boolean) => {
        shown: boolean
    } // personsLogic
    cancel: () => {
        value: true
    }
    execute: () => any
    executeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    executeSuccess: (
        executed: boolean,
        payload?: any
    ) => {
        executed: boolean
        payload?: any
    }
    setDistinctIdsToSplit: (ids: string[]) => {
        ids: string[]
    }
    setSelectedPersonToAssignSplit: (id: string) => {
        id: string
    }
    setSplitMode: (mode: SplitMode) => {
        mode: SplitMode
    }
}

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

export type mergeSplitPersonLogicType = MakeLogicType<
    mergeSplitPersonLogicValues,
    mergeSplitPersonLogicActions,
    SplitPersonLogicProps,
    mergeSplitPersonLogicMeta
>

export const mergeSplitPersonLogic = kea<mergeSplitPersonLogicType>([
    props({} as SplitPersonLogicProps),
    key((props) => `${props.person.id ?? 'new'}`),
    path((key) => ['scenes', 'persons', 'mergeSplitPersonLogic', key]),
    connect((props: SplitPersonLogicProps) => ({
        actions: [
            personsLogic({ syncWithUrl: true, urlId: props.urlId }),
            ['setListFilters', 'loadPersons', 'setPerson', 'setSplitMergeModalShown'],
        ],
        values: [personsLogic({ syncWithUrl: true, urlId: props.urlId }), ['persons']],
    })),
    actions({
        setSelectedPersonToAssignSplit: (id: string) => ({ id }),
        setSplitMode: (mode: SplitMode) => ({ mode }),
        setDistinctIdsToSplit: (ids: string[]) => ({ ids }),
        cancel: true,
    }),
    loaders(({ values, actions }) => ({
        executed: [
            false,
            {
                execute: async () => {
                    const payload =
                        values.splitMode === 'partial'
                            ? { distinct_ids_to_split: values.distinctIdsToSplit }
                            : values.selectedPersonToAssignSplit
                              ? { main_distinct_id: values.selectedPersonToAssignSplit }
                              : {}
                    // personsSplitCreate needs a project id that this logic does not hold.
                    // 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 splitAction = await api.create('api/person/' + values.person.id + '/split/', payload)
                    if (splitAction.success) {
                        lemonToast.success(
                            'Person succesfully split. This may take up to a couple of minutes to complete.'
                        )
                        posthog.capture('split person started', { merge_count: values.person.distinct_ids.length })
                        actions.setSplitMergeModalShown(false)
                        router.actions.push('/persons')
                        return true
                    }
                    return false
                },
            },
        ],
    })),
    reducers(({ props }) => ({
        person: [props.person, {}],
        selectedPersonToAssignSplit: [
            null as null | string,
            {
                setSelectedPersonToAssignSplit: (_, { id }) => id,
            },
        ],
        splitMode: [
            'all' as SplitMode,
            {
                setSplitMode: (_, { mode }) => mode,
            },
        ],
        distinctIdsToSplit: [
            [] as string[],
            {
                setDistinctIdsToSplit: (_, { ids }) => ids,
            },
        ],
    })),
    listeners(({ actions, values }) => ({
        setListFilters: () => {
            actions.loadPersons()
        },
        cancel: () => {
            if (!values.executedLoading) {
                actions.setSplitMergeModalShown(false)
            }
        },
    })),
    events(({ actions }) => ({
        afterMount: [actions.loadPersons],
    })),
])