: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, connect, events, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import type { SharedMetric } from './sharedMetricLogic'
export const PAGE_SIZE = 100
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharedMetricsLogicValues {
currentProjectId: number | string // teamLogic
count: number
page: number
savingTagsMetricId: SharedMetric['id'] | null
searchTerm: string
sharedMetrics: SharedMetric[]
sharedMetricsLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharedMetricsLogicActions {
deleteSharedMetric: (metricId: SharedMetric['id']) => {
metricId: number
}
loadSharedMetrics: (_: void) => void
loadSharedMetricsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadSharedMetricsSuccess: (
sharedMetrics: SharedMetric[],
payload?: void
) => {
sharedMetrics: SharedMetric[]
payload?: void
}
setCount: (count: number) => {
count: number
}
setPage: (page: number) => {
page: number
}
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
updateSharedMetricTags: (
metricId: SharedMetric['id'],
tags: string[]
) => {
metricId: number
tags: string[]
}
}
export type sharedMetricsLogicType = MakeLogicType<sharedMetricsLogicValues, sharedMetricsLogicActions>
export const sharedMetricsLogic = kea<sharedMetricsLogicType>([
path(['scenes', 'experiments', 'sharedMetricsLogic']),
connect(() => ({ values: [teamLogic, ['currentProjectId']] })),
actions({
updateSharedMetricTags: (metricId: SharedMetric['id'], tags: string[]) => ({ metricId, tags }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setPage: (page: number) => ({ page }),
setCount: (count: number) => ({ count }),
deleteSharedMetric: (metricId: SharedMetric['id']) => ({ metricId }),
}),
reducers({
savingTagsMetricId: [
null as SharedMetric['id'] | null,
{
updateSharedMetricTags: (_, { metricId }) => metricId,
loadSharedMetricsSuccess: () => null,
loadSharedMetricsFailure: () => null,
},
],
searchTerm: [
'',
{
setSearchTerm: (_, { searchTerm }) => searchTerm,
},
],
page: [
1,
{
setPage: (_, { page }) => page,
setSearchTerm: () => 1,
},
],
count: [
0,
{
setCount: (_, { count }) => count,
},
],
}),
loaders(({ values, actions }) => ({
sharedMetrics: [
[] as SharedMetric[],
{
loadSharedMetrics: async (_: void, breakpoint) => {
const params = toParams({
limit: PAGE_SIZE,
offset: (values.page - 1) * PAGE_SIZE,
search: values.searchTerm || undefined,
})
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentSavedMetricsList() from 'products/experiments/frontend/generated/api' instead.
const response: CountedPaginatedResponse<SharedMetric> = await api.get(
`api/projects/${values.currentProjectId}/experiment_saved_metrics?${params}`
)
// Discard stale responses that resolve after a newer search has fired
breakpoint()
actions.setCount(response.count)
return response.results
},
},
],
})),
listeners(({ actions, values }) => ({
setPage: async () => {
actions.loadSharedMetrics()
},
setSearchTerm: async (_, breakpoint) => {
await breakpoint(300)
actions.loadSharedMetrics()
},
updateSharedMetricTags: async ({ metricId, tags }) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentSavedMetricsPartialUpdate() from 'products/experiments/frontend/generated/api' instead.
await api.update(`api/projects/${values.currentProjectId}/experiment_saved_metrics/${metricId}`, {
tags,
})
actions.loadSharedMetrics()
} catch {
lemonToast.error('Failed to save tags')
actions.loadSharedMetrics()
}
},
deleteSharedMetric: async ({ metricId }) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. experimentSavedMetricsDestroy() from 'products/experiments/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
await api.delete(`api/projects/${values.currentProjectId}/experiment_saved_metrics/${metricId}`)
lemonToast.success('Shared metric deleted successfully')
actions.loadSharedMetrics()
} catch {
lemonToast.error('Failed to delete shared metric')
}
},
})),
events(({ actions }) => ({
afterMount: () => {
actions.loadSharedMetrics()
},
})),
])