: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, kea, key, path, props, selectors } from 'kea'
import { lazyLoaders } from 'kea-loaders'
import posthog from 'posthog-js'
import api from 'lib/api'
import { hogql } from 'lib/utils/hogql'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
import { Breadcrumb, PersonType } from '~/types'
import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from 'products/customer_analytics/frontend/constants'
import { getHogqlQueryStringForPersonId, parsePersonFromHogQLRow } from '../person-utils'
export interface PersonLogicProps {
id: string | undefined
distinctId: string | undefined
}
export interface Info {
sessionCount: number
eventCount: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personLogicValues {
breadcrumbs: Breadcrumb[]
info: Info | null
infoLoading: boolean
person: PersonType | null
personLoading: boolean
revenueData: {
lifetimeValue: number | null
mrr: number | null
} | null
revenueDataLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personLogicActions {
loadInfo: () => {
value: true
}
loadInfoFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadInfoSuccess: (
info: Info | null,
payload?: {
value: true
}
) => {
info: Info | null
payload?: {
value: true
}
}
loadPerson: () => {
value: true
}
loadPersonFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadPersonSuccess: (
person: PersonType | null,
payload?: {
value: true
}
) => {
person: PersonType | null
payload?: {
value: true
}
}
loadRevenueData: () => any
loadRevenueDataFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadRevenueDataSuccess: (
revenueData: {
lifetimeValue: any
mrr: any
} | null,
payload?: any
) => {
revenueData: {
lifetimeValue: any
mrr: any
} | null
payload?: any
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface personLogicMeta {
key: string
}
export type personLogicType = MakeLogicType<personLogicValues, personLogicActions, PersonLogicProps, personLogicMeta>
export const personLogic = kea<personLogicType>([
props({} as PersonLogicProps),
key((props) => props.distinctId ?? props.id ?? 'undefined'),
path((key) => ['scenes', 'persons', 'personLogic', key]),
actions({
loadPerson: true,
loadInfo: true,
}),
selectors(() => ({
breadcrumbs: [
() => [],
(): Breadcrumb[] => {
const breadcrumbs: Breadcrumb[] = [
{
key: Scene.Person,
name: sceneConfigurations[Scene.Person].name,
iconType: sceneConfigurations[Scene.Person].iconType || 'default_icon_type',
},
]
return breadcrumbs
},
],
})),
lazyLoaders(({ props }) => ({
person: [
null as PersonType | null,
{
loadPerson: async (): Promise<PersonType | null> => {
if (props.distinctId != null) {
const response = await api.persons.list({ distinct_id: props.distinctId })
const person = response.results[0]
if (person != null) {
return person
}
}
if (props.id == null) {
return null
}
const queryResponse = await api.query<HogQLQuery>(
{
kind: NodeKind.HogQLQuery,
query: getHogqlQueryStringForPersonId(),
values: { id: props.id },
tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
},
{ refresh: 'blocking' }
)
const row = queryResponse?.results?.[0]
if (row == null) {
return null
}
return parsePersonFromHogQLRow(row)
},
},
],
info: [
null as Info | null,
{
loadInfo: async (): Promise<Info | null> => {
if (!props.id) {
return null
}
const infoQuery = hogql`
SELECT
count(DISTINCT $session_id) as session_count,
count(*) as event_count
FROM events
WHERE
person_id = ${props.id}
AND timestamp >= now() - interval 30 day
`
try {
const response = await api.queryHogQL(infoQuery, CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS)
const row = response.results?.[0]
if (!row) {
return {
sessionCount: 0,
eventCount: 0,
}
}
const [sessionCount, eventCount] = row
return { sessionCount, eventCount }
} catch (error: any) {
posthog.captureException(error)
return {
sessionCount: 0,
eventCount: 0,
}
}
},
},
],
revenueData: [
null as { mrr: number | null; lifetimeValue: number | null } | null,
{
loadRevenueData: async () => {
try {
const result = await api.query({
kind: NodeKind.HogQLQuery,
tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
query: `
SELECT mrr, revenue
FROM persons_revenue_analytics
WHERE person_id = {personId}
`,
values: { personId: props.id },
})
const row = (result as any).results?.[0]
if (!row) {
return null
}
return {
mrr: row[0] ?? null,
lifetimeValue: row[1] ?? null,
}
} catch (error) {
posthog.captureException(error, { tag: 'person_revenue_analytics_data_query_failed' })
return null
}
},
},
],
})),
])