: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, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { PaginationManual, lemonToast } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { delay } from 'lib/utils/async'
import { cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { cohortSavedToast } from 'scenes/cohorts/cohortSavedToast'
import { projectLogic } from 'scenes/projectLogic'
import { ActorsQuery } from '~/queries/schema/schema-general'
import { CohortType } from '~/types'
const COHORTS_PER_PAGE = 100
export interface CohortFilters {
search?: string
page?: number
type: 'static' | 'dynamic'
}
const DEFAULT_COHORT_FILTERS: CohortFilters = {
search: undefined,
page: 1,
type: 'static',
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface saveToCohortModalContentLogicValues {
currentProjectId: number | null // projectLogic
cohortFilters: CohortFilters
cohorts: CountedPaginatedResponse<CohortType>
cohortsLoading: boolean
count: number
pagination: PaginationManual
paramsFromFilters: {
limit: number
offset: number
page?: number | undefined
search?: string | undefined
type: 'dynamic' | 'static'
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface saveToCohortModalContentLogicActions {
loadCohorts: () => any
loadCohortsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadCohortsSuccess: (
cohorts: {
count: number
results: CohortType[]
},
payload?: any
) => {
cohorts: {
count: number
results: CohortType[]
}
payload?: any
}
saveQueryToCohort: (
cohort: CohortType,
query: ActorsQuery
) => {
cohort: CohortType
query: ActorsQuery
}
setCohortFilters: (filters: Partial<CohortFilters>) => {
filters: Partial<CohortFilters>
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface saveToCohortModalContentLogicMeta {
__keaTypeGenInternalSelectorTypes: {
count: (cohorts: CountedPaginatedResponse<CohortType>) => number
paramsFromFilters: (cohortFilters: CohortFilters) => {
limit: number
offset: number
page?: number | undefined
search?: string | undefined
type: 'dynamic' | 'static'
}
pagination: (cohortFilters: CohortFilters, count: number) => PaginationManual
}
}
export type saveToCohortModalContentLogicType = MakeLogicType<
saveToCohortModalContentLogicValues,
saveToCohortModalContentLogicActions,
Record<string, any>,
saveToCohortModalContentLogicMeta
>
export const saveToCohortModalContentLogic = kea<saveToCohortModalContentLogicType>([
path(['lib', 'components', 'SaveToCohortModal', 'saveToCohortModalContentLogic']),
connect(() => ({
values: [projectLogic, ['currentProjectId']],
})),
actions({
setCohortFilters: (filters: Partial<CohortFilters>) => ({ filters }),
saveQueryToCohort: (cohort: CohortType, query: ActorsQuery) => ({ cohort, query }),
}),
reducers({
cohorts: [{ count: 0, results: [] }],
cohortFilters: [
DEFAULT_COHORT_FILTERS,
{
setCohortFilters: (state, { filters }) => {
return { ...state, ...filters }
},
},
],
}),
loaders(({ values }) => ({
cohorts: {
__default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,
loadCohorts: async () => {
const response = await api.cohorts.listPaginated({
...values.paramsFromFilters,
})
return {
count: response.count,
results: response.results,
}
},
},
})),
selectors(({ actions }) => ({
count: [(selectors) => [selectors.cohorts], (cohorts: CountedPaginatedResponse<CohortType>) => cohorts.count],
paramsFromFilters: [
(s) => [s.cohortFilters],
(filters: CohortFilters) => ({
...filters,
limit: COHORTS_PER_PAGE,
offset: filters.page ? (filters.page - 1) * COHORTS_PER_PAGE : 0,
}),
],
pagination: [
(s) => [s.cohortFilters, s.count],
(filters: CohortFilters, count: number): PaginationManual => {
return {
controlled: true,
pageSize: COHORTS_PER_PAGE,
currentPage: filters.page || 1,
entryCount: count,
onBackward: () => actions.setCohortFilters({ page: filters.page != null ? filters.page - 1 : 1 }),
onForward: () => actions.setCohortFilters({ page: filters.page != null ? filters.page + 1 : 1 }),
}
},
],
})),
listeners(({ actions, values }) => ({
setCohortFilters: async () => {
actions.loadCohorts()
},
saveQueryToCohort: async ({ cohort, query }) => {
const toastId = `save-cohort-${cohort.id}-${Date.now()}`
try {
lemonToast.info('Saving cohort...', { toastId, autoClose: false })
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use cohortsPartialUpdate() from 'products/cohorts/frontend/generated/api' instead.
await api.update(`api/projects/${values.currentProjectId}/cohorts/${cohort.id}`, {
query: query,
})
const mountedCohortEditLogic = cohortEditLogic.findMounted({ id: cohort.id })
await mountedCohortEditLogic?.actions.updateCohortCount()
await delay(500) // just in case the toast is too fast
lemonToast.dismiss(toastId)
cohortSavedToast(cohort, 'query_results', `${toastId}-success`)
} catch (error: any) {
console.error('Save to cohort failed:', error)
lemonToast.dismiss(toastId)
lemonToast.error(error.detail || 'Save to cohort failed')
}
},
})),
afterMount(({ actions }) => {
actions.loadCohorts()
}),
])