: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, connect, kea, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { hogql } from 'lib/utils/hogql'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { sidePanelContextLogic } from '~/layout/navigation-3000/sidepanel/sidePanelContextLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
import { membersLogic } from '~/models/membersLogic'
import { ActivityScope, SidePanelTab } from '~/types'
import type { OrganizationMemberType } from '../../../types'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metalyticsLogicValues {
members: OrganizationMemberType[] | null // membersLogic
scenePanelOpen: boolean // sceneLayoutLogic
sceneSidePanelContext: SidePanelSceneContext // sidePanelContextLogic
selectedTab: SidePanelTab | null // sidePanelStateLogic
sidePanelOpen: boolean // sidePanelStateLogic
currentProjectId: number | string // teamLogic
instanceId: string | null
recentUserMembers: OrganizationMemberType[]
recentUsers: string[]
recentUsersLoading: boolean
scope: string | undefined
statsInstanceId: string | null
viewCount: {
users: number
views: number
} | null
viewCountLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metalyticsLogicActions {
loadUsersLast30days: (_: any) => any
loadUsersLast30daysFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadUsersLast30daysSuccess: (
recentUsers: string[],
payload?: any
) => {
recentUsers: string[]
payload?: any
}
loadViewCount: (_: any) => any
loadViewCountFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadViewCountSuccess: (
viewCount: {
users: number
views: number
} | null,
payload?: any
) => {
viewCount: {
users: number
views: number
} | null
payload?: any
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metalyticsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
instanceId: (sceneSidePanelContext: SidePanelSceneContext) => string | null
scope: (sceneSidePanelContext: SidePanelSceneContext) => string | undefined
statsInstanceId: (
instanceId: string | null,
scope: string | undefined,
scenePanelOpen: boolean,
sidePanelOpen: boolean,
selectedTab: SidePanelTab | null
) => string | null
recentUserMembers: (recentUsers: string[], members: OrganizationMemberType[] | null) => OrganizationMemberType[]
}
}
export type metalyticsLogicType = MakeLogicType<
metalyticsLogicValues,
metalyticsLogicActions,
Record<string, any>,
metalyticsLogicMeta
>
export const metalyticsLogic = kea<metalyticsLogicType>([
path(['lib', 'components', 'metalytics', 'metalyticsLogic']),
connect(() => ({
values: [
sidePanelContextLogic,
['sceneSidePanelContext'],
membersLogic,
['members'],
teamLogic,
['currentProjectId'],
sceneLayoutLogic,
['scenePanelOpen'],
sidePanelStateLogic,
['sidePanelOpen', 'selectedTab'],
],
})),
loaders(({ values }) => ({
viewCount: [
null as { views: number; users: number } | null,
{
loadViewCount: async (_, breakpoint) => {
if (!values.statsInstanceId) {
return null
}
const query = hogql`
SELECT SUM(count) AS count, COUNT(DISTINCT app_source_id) AS unique_users
FROM app_metrics
WHERE app_source = 'metalytics'
AND instance_id = ${values.instanceId}`
const currentScene = sceneLogic.findMounted()?.values.activeSceneId ?? 'Metalytics'
const response = await api.queryHogQL(
query,
{ scene: currentScene, productKey: 'platform_and_support' },
{ refresh: 'async' }
)
breakpoint()
const result = response.results as number[][] | undefined
return {
views: result?.[0]?.[0] ?? 0,
users: result?.[0]?.[1] ?? 0,
}
},
},
],
recentUsers: [
[] as string[],
{
loadUsersLast30days: async (_, breakpoint) => {
if (!values.statsInstanceId) {
return []
}
const query = hogql`
SELECT DISTINCT app_source_id
FROM app_metrics
WHERE app_source = 'metalytics'
AND instance_id = ${values.instanceId}
AND timestamp >= NOW() - INTERVAL 30 DAY
ORDER BY timestamp DESC`
const currentScene = sceneLogic.findMounted()?.values.activeSceneId ?? 'Metalytics'
const response = await api.queryHogQL(
query,
{ scene: currentScene, productKey: 'platform_and_support' },
{ refresh: 'async' }
)
breakpoint()
return (response.results?.map((result) => result[0]) ?? []) as string[]
},
},
],
})),
selectors({
instanceId: [
(s) => [s.sceneSidePanelContext],
(sidePanelContext: SidePanelSceneContext) =>
sidePanelContext?.activity_item_id
? `${sidePanelContext.activity_scope}:${sidePanelContext.activity_item_id}`
: null,
],
scope: [
(s) => [s.sceneSidePanelContext],
(sidePanelContext: SidePanelSceneContext) => sidePanelContext?.activity_scope,
],
statsInstanceId: [
(s) => [s.instanceId, s.scope, s.scenePanelOpen, s.sidePanelOpen, s.selectedTab],
(
instanceId: string | null,
scope: string | undefined,
scenePanelOpen: boolean,
sidePanelOpen: boolean,
selectedTab: SidePanelTab | null
): string | null =>
scope !== ActivityScope.INSIGHT ||
scenePanelOpen ||
(sidePanelOpen && selectedTab === SidePanelTab.Activity)
? instanceId
: null,
],
recentUserMembers: [
(s) => [s.recentUsers, s.members],
(recentUsers: string[], members: import('../../../types').OrganizationMemberType[] | null) => {
if (!members || !recentUsers) {
return []
}
// Filter members whose IDs match the recentUsers array
const filteredMembers = members.filter((member) => recentUsers.includes(String(member.user.id)))
return filteredMembers
},
],
}),
subscriptions(({ actions, values }) => ({
statsInstanceId: () => {
actions.loadViewCount(undefined)
actions.loadUsersLast30days(undefined)
},
instanceId: async (instanceId) => {
if (instanceId) {
// 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.
void api.create(`/api/projects/${values.currentProjectId}/metalytics/`, {
metric_name: 'viewed',
instance_id: instanceId,
})
}
},
})),
])