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.

7.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'

import { Dayjs, dayjsUtcToTimezone } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'

import { Properties } from '~/legacy-plugin-scaffold'
import { InsightActorsQuery } from '~/queries/schema/schema-general'
import { PersonActorType } from '~/types'

import { personsPropertiesTimelineCreate } from 'products/persons/frontend/generated/api'
import type {
    PropertiesTimelineRequestApi,
    PropertiesTimelineResponseApi,
} from 'products/persons/frontend/generated/api.schemas'

export interface PropertiesTimelinePoint {
    timestamp: Dayjs
    properties: Properties
    relevantEventCount: number
}

export interface PropertiesTimelineProps {
    actor: PersonActorType
    /** The actors query of the clicked Trends data point. */
    query: InsightActorsQuery
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface propertiesTimelineLogicValues {
    currentTeamId: number | null // teamLogic
    timezone: string // teamLogic
    crucialPropertyKeys: (keyof Properties)[]
    dateRange: [Dayjs, Dayjs] | null
    points: PropertiesTimelinePoint[]
    result: PropertiesTimelineResponseApi | null
    resultLoading: boolean
    selectedPointIndex: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface propertiesTimelineLogicActions {
    loadResult: () => any
    loadResultFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadResultSuccess: (
        result: PropertiesTimelineResponseApi,
        payload?: any
    ) => {
        result: PropertiesTimelineResponseApi
        payload?: any
    }
    setSelectedPointIndex: (index: number | null) => {
        index: number | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface propertiesTimelineLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        points: (result: PropertiesTimelineResponseApi | null, timezone: string) => PropertiesTimelinePoint[]
        crucialPropertyKeys: (result: PropertiesTimelineResponseApi | null) => (keyof Properties)[]
        dateRange: (result: PropertiesTimelineResponseApi | null, timezone: string) => [Dayjs, Dayjs] | null
    }
}

export type propertiesTimelineLogicType = MakeLogicType<
    propertiesTimelineLogicValues,
    propertiesTimelineLogicActions,
    PropertiesTimelineProps,
    propertiesTimelineLogicMeta
>

export const propertiesTimelineLogic = kea<propertiesTimelineLogicType>([
    path(['lib', 'components', 'PropertiesTimeline', 'propertiesTimelineLogic']),
    props({} as PropertiesTimelineProps),
    key((props) => `${props.actor.id}-${JSON.stringify(props.query)}`),
    connect(() => ({
        values: [teamLogic, ['currentTeamId', 'timezone']],
    })),
    actions({
        setSelectedPointIndex: (index: number | null) => ({ index }),
    }),
    reducers({
        selectedPointIndex: [
            null as number | null,
            {
                setSelectedPointIndex: (_, { index }) => index,
                loadResultSuccess: (_, { result }) =>
                    result.crucial_property_keys.length > 0 && result.points.length > 0
                        ? result.points.length - 1
                        : null,
            },
        ],
    }),
    loaders(({ values, props }) => ({
        // This reducer is for loading convenience, for actual data use `points`, `crucialPropertyKeys`, and `dateRange`
        result: [
            null as PropertiesTimelineResponseApi | null,
            {
                loadResult: async () => {
                    const response = await personsPropertiesTimelineCreate(
                        String(values.currentTeamId),
                        props.actor.id,
                        // The OpenAPI query type differs from the query schema in details such as funnel `binCount`
                        { query: props.query as PropertiesTimelineRequestApi['query'] }
                    )
                    if (response.points.length === 0) {
                        // It should not be possible for a properties timeline to have zero points, as all actors
                        // shown in the actors modal must have at least one relevant event in the period.
                        // pinned: error tracking groups by this message, so keep it unchanged.
                        posthog.captureException(new Error('Properties Timeline returned no points'), {
                            tags: { 'team.id': values.currentTeamId },
                            extra: { query: props.query },
                        })
                    }
                    return response
                },
            },
        ],
    })),
    selectors({
        points: [
            (s) => [s.result, s.timezone],
            (result: PropertiesTimelineResponseApi | null, timezone: string) =>
                result
                    ? result.points.map(
                          (point): PropertiesTimelinePoint => ({
                              relevantEventCount: point.relevant_event_count,
                              properties: point.properties,
                              timestamp: dayjsUtcToTimezone(point.timestamp, timezone),
                          })
                      )
                    : [],
        ],
        crucialPropertyKeys: [
            (s) => [s.result],
            (result: PropertiesTimelineResponseApi | null): (keyof Properties)[] =>
                result ? result.crucial_property_keys : [],
        ],
        dateRange: [
            (s) => [s.result, s.timezone],
            (result: PropertiesTimelineResponseApi | null, timezone: string): [Dayjs, Dayjs] | null =>
                result && [
                    dayjsUtcToTimezone(result.effective_date_from, timezone),
                    dayjsUtcToTimezone(result.effective_date_to, timezone),
                ],
        ],
    }),
    listeners(({ props, values }) => ({
        loadResultSuccess: ({ result }) => {
            // pinned: analytics event and property names, renaming breaks the usage insights
            posthog.capture('insight person modal properties timeline loaded', {
                source_kind: props.query.source.kind,
                has_key_properties: result.crucial_property_keys.length > 0,
                key_property_count: result.crucial_property_keys.length,
                point_count: result.points.length,
            })
        },
        setSelectedPointIndex: ({ index }) => {
            // pinned: analytics event and property names, renaming breaks the usage insights
            posthog.capture('insight person modal properties timeline point selected', {
                source_kind: props.query.source.kind,
                point_count: values.points.length,
                selected_present: index !== null,
            })
        },
    })),
    afterMount(({ actions }) => {
        actions.loadResult()
    }),
])