: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, key, listeners, path, props } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import { truncate } from 'lib/utils/strings'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { buildSurveyRespondentsQuery } from 'scenes/surveys/utils'
import { teamLogic } from 'scenes/teamLogic'
import { performQuery } from '~/queries/query'
import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
import { AnyPropertyFilter, EventPropertyFilter, Survey } from '~/types'
import { cohortsCreate } from 'products/cohorts/frontend/generated/api'
import type { CohortApi } from 'products/cohorts/frontend/generated/api.schemas'
import {
captureMessageAudienceClicked,
cohortAudienceProperties,
} from 'products/workflows/frontend/MessageAudience/messageAudience'
import { openMessageAudience } from 'products/workflows/frontend/MessageAudience/messageAudienceWarnings'
import { draftMessage } from 'products/workflows/frontend/MessageAudience/messageDrafts'
import type { NewSurvey } from '../constants'
// pinned: sent as the broadcast's entry_source and the click event's source, so renaming it splits the history
const SOURCE = 'survey_respondents'
const MAX_NAME_LENGTH = 200
export interface SurveyRespondentsBroadcastLogicProps {
surveyId: string
}
function respondentsQuery(
survey: Survey,
select: 'count' | 'people',
filters: {
answerFilters: EventPropertyFilter[]
timestampFilter: string
archivedResponsesFilter: string
propertyFilters: AnyPropertyFilter[]
}
): HogQLQuery {
return {
kind: NodeKind.HogQLQuery,
query: buildSurveyRespondentsQuery(survey, filters, select),
filters: { properties: filters.propertyFilters },
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyRespondentsBroadcastLogicValues {
answerFilters: EventPropertyFilter[] // surveyLogic
archivedResponsesFilter: string // surveyLogic
hasActiveFilters: boolean // surveyLogic
propertyFilters: AnyPropertyFilter[] // surveyLogic
survey: NewSurvey | Survey // surveyLogic
timestampFilter: string // surveyLogic
currentProjectId: number | string // teamLogic
respondentsCohort: CohortApi | null
respondentsCohortLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyRespondentsBroadcastLogicActions {
emailRespondents: (_: any) => any
emailRespondentsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
emailRespondentsSuccess: (
respondentsCohort: CohortApi | null,
payload?: any
) => {
respondentsCohort: CohortApi | null
payload?: any
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyRespondentsBroadcastLogicMeta {
key: string
}
export type surveyRespondentsBroadcastLogicType = MakeLogicType<
surveyRespondentsBroadcastLogicValues,
surveyRespondentsBroadcastLogicActions,
SurveyRespondentsBroadcastLogicProps,
surveyRespondentsBroadcastLogicMeta
>
export const surveyRespondentsBroadcastLogic = kea<surveyRespondentsBroadcastLogicType>([
path((key) => ['scenes', 'surveys', 'components', 'surveyRespondentsBroadcastLogic', key]),
props({} as SurveyRespondentsBroadcastLogicProps),
key((props) => props.surveyId),
connect((props: SurveyRespondentsBroadcastLogicProps) => ({
values: [
surveyLogic({ id: props.surveyId }),
[
'survey',
'answerFilters',
'timestampFilter',
'archivedResponsesFilter',
'propertyFilters',
'hasActiveFilters',
],
teamLogic,
['currentProjectId'],
],
})),
loaders(({ values }) => ({
respondentsCohort: [
null as CohortApi | null,
{
emailRespondents: async (_, breakpoint) => {
const survey = values.survey as Survey
const filters = {
answerFilters: values.answerFilters,
timestampFilter: values.timestampFilter,
archivedResponsesFilter: values.archivedResponsesFilter,
propertyFilters: values.propertyFilters,
}
const counted = await performQuery(respondentsQuery(survey, 'count', filters))
// Leaving the survey unmounts this logic, and the breakpoint then stops the wizard from opening.
breakpoint()
const [people, withEmail] = (counted.results?.[0] ?? [0, 0]) as [number, number]
if (!people) {
lemonToast.info(
values.hasActiveFilters
? 'No responses match these filters, so there is no one to email.'
: 'No one has responded yet, so there is no one to email.'
)
return null
}
if (!withEmail) {
lemonToast.info('None of these respondents has an email address.')
return null
}
const cohort = await cohortsCreate(String(values.currentProjectId), {
name: truncate(
`${values.hasActiveFilters ? 'Filtered respondents' : 'Respondents'} to ${survey.name}`,
MAX_NAME_LENGTH
),
is_static: true,
query: respondentsQuery(survey, 'people', filters),
})
breakpoint()
await openMessageAudience(
{
properties: cohortAudienceProperties(cohort),
source: SOURCE,
broadcastName: truncate(`Following up on ${survey.name}`, MAX_NAME_LENGTH),
broadcastEmail: draftMessage({ kind: 'survey_responded' }),
draftSource: { source: 'survey', source_id: survey.id },
},
'broadcast'
)
return cohort
},
},
],
})),
listeners(() => ({
// The click on the entry point, before any outcome, so abandoned attempts count too.
emailRespondents: () => captureMessageAudienceClicked(SOURCE, 'broadcast'),
emailRespondentsFailure: () => {
lemonToast.error("Couldn't save these respondents. Try again.")
},
})),
])