Skip to content

: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.

feat(surveys): email the respondents a survey's filters show (#120554)

Daniel Marchukc5623ec1d049
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
index 970962532435..fd9395a31bd8 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
@@ -28,6 +28,7 @@ import { SurveyQuestionVisualization } from 'scenes/surveys/components/question-
import { SurveyFeedbackButton } from 'scenes/surveys/components/SurveyFeedbackButton'
import { SurveyFollowUpWorkflowButton } from 'scenes/surveys/components/SurveyFollowUpWorkflowButton'
import { SurveyNotifications } from 'scenes/surveys/components/SurveyNotifications'
+import { SurveyRespondentsBroadcastButton } from 'scenes/surveys/components/SurveyRespondentsBroadcastButton'
import { DuplicateToProjectModal } from 'scenes/surveys/DuplicateToProjectModal'
import { useSurveyResponseColumns } from 'scenes/surveys/hooks/useSurveyResponseColumns'
import {
@@ -649,6 +650,13 @@ function SurveySummaryContent({ onViewResponses }: { onViewResponses: () => void
/>
)
+ const resultsActions = (
+ <>
+ {survey.id !== 'new' && <SurveyRespondentsBroadcastButton surveyId={survey.id} />}
+ {exportButton}
+ </>
+ )
+
if (!isRefreshingResults && !atLeastOneResponse) {
return (
<div className="px-4 pb-4">
@@ -673,7 +681,7 @@ function SurveySummaryContent({ onViewResponses }: { onViewResponses: () => void
return (
<div className="px-4 pb-4">
<div className="mx-auto w-full max-w-[1200px] space-y-6">
- <SurveyResultsFiltersBar actions={exportButton} />
+ <SurveyResultsFiltersBar actions={resultsActions} />
<SurveyResultsRefreshStatus visible={isRefreshingResults} />
<div
aria-busy={isRefreshingResults}
@@ -743,7 +751,9 @@ function SurveyResponsesContent(): JSX.Element {
return (
<div className="px-4 pb-4 space-y-6">
- <SurveyResultsFiltersBar />
+ <SurveyResultsFiltersBar
+ actions={survey.id !== 'new' ? <SurveyRespondentsBroadcastButton surveyId={survey.id} /> : undefined}
+ />
<SurveyResultsRefreshStatus visible={isRefreshingResults} />
{isInitialSurveyLoad ? (
<LemonSkeleton />
diff --git a/frontend/src/scenes/surveys/components/SurveyRespondentsBroadcastButton.tsx b/frontend/src/scenes/surveys/components/SurveyRespondentsBroadcastButton.tsx
new file mode 100644
index 000000000000..c2558ffe20c1
--- /dev/null
+++ b/frontend/src/scenes/surveys/components/SurveyRespondentsBroadcastButton.tsx
@@ -0,0 +1,28 @@
+import { useActions, useValues } from 'kea'
+
+import { IconSend } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { messageAudienceAccessDisabledReason } from 'products/workflows/frontend/MessageAudience/messageAudience'
+
+import { surveyRespondentsBroadcastLogic } from './surveyRespondentsBroadcastLogic'
+
+export function SurveyRespondentsBroadcastButton({ surveyId }: { surveyId: string }): JSX.Element {
+ const logic = surveyRespondentsBroadcastLogic({ surveyId })
+ const { respondentsCohortLoading, hasActiveFilters } = useValues(logic)
+ const { emailRespondents } = useActions(logic)
+ return (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconSend />}
+ onClick={emailRespondents}
+ loading={respondentsCohortLoading}
+ disabledReason={messageAudienceAccessDisabledReason()}
+ tooltip="Send a one-time email to the people behind the responses shown"
+ data-attr="survey-email-respondents"
+ >
+ {hasActiveFilters ? 'Email these respondents' : 'Email respondents'}
+ </LemonButton>
+ )
+}
diff --git a/frontend/src/scenes/surveys/components/surveyRespondentsBroadcastLogic.ts b/frontend/src/scenes/surveys/components/surveyRespondentsBroadcastLogic.ts
new file mode 100644
index 000000000000..0ee0fa97a453
--- /dev/null
+++ b/frontend/src/scenes/surveys/components/surveyRespondentsBroadcastLogic.ts
@@ -0,0 +1,175 @@
+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.")
+ },
+ })),
+])
diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.ts
index e3dbbb72b347..ea1d935282bd 100644
--- a/frontend/src/scenes/surveys/utils.test.ts
+++ b/frontend/src/scenes/surveys/utils.test.ts
@@ -23,6 +23,7 @@ import {
buildAggregateQuery,
buildOpenEndedQuery,
buildSurveyExampleInvocationGlobals,
+ buildSurveyRespondentsQuery,
buildSurveyResponsesExportQuery,
buildSurveyOptionalBooleanPropertyFilter,
buildSurveyTimestampFilter,
@@ -1302,6 +1303,29 @@ describe('survey utils', () => {
expect(query).toContain("uuid NOT IN ('archived-uuid')")
})
+ it.each(['count', 'people'] as const)(
+ 'keeps people who dismissed after answering in the %s respondents query',
+ (select) => {
+ const survey = buildSurvey(true)
+
+ const query = buildSurveyRespondentsQuery(survey, buildFilters(survey), select)
+
+ // The event filter already drops dismissals without an answer, so a filter on the merged
+ // outcome would only drop people whose answers the results still show.
+ expect(query).toContain("'survey dismissed', 'survey abandoned'")
+ expect(query).not.toContain("outcome != 'dismissed'")
+ }
+ )
+
+ it('counts respondents with an email from the email alone, not the whole person properties', () => {
+ const survey = buildSurvey(true)
+
+ const query = buildSurveyRespondentsQuery(survey, buildFilters(survey), 'count')
+
+ expect(query).toContain('argMax(respondent_email, tuple(timestamp, event_uuid))')
+ expect(query).not.toContain('person_properties')
+ })
+
it('counts an unanswered optional single choice when the merge yields null instead of an empty string', () => {
const survey = {
...buildSurvey(true),
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index 817350982d14..9688863973ac 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -1050,6 +1050,27 @@ export function buildSurveyResponsesQuery(
return `SELECT ${columns.join(',\n')} FROM (${merged}) ORDER BY submitted_at DESC`
}
+/**
+ * The people behind the responses the current filters show. No outcome filter is needed:
+ * `buildSurveyResponseEventFilter` already drops dismissals that carry no answer, and a dismissal
+ * after an answer still shows in the results.
+ */
+export function buildSurveyRespondentsQuery(
+ survey: Survey,
+ filters: SurveyQueryFilters,
+ select: 'count' | 'people'
+): string {
+ if (select === 'people') {
+ const merged = buildMergedSubmissionsSubquery(survey, filters, getAnswerableQuestions(survey))
+ return `SELECT DISTINCT person_id FROM (${merged})`
+ }
+ // Read only the email so the merge does not carry each submission's whole person properties blob through argMax.
+ const merged = buildMergedSubmissionsSubquery(survey, filters, getAnswerableQuestions(survey), {
+ propertyReads: [{ alias: 'respondent_email', expression: 'person.properties.email' }],
+ })
+ return `SELECT count(), countIf(notEmpty(coalesce(respondent_email, ''))) FROM (${merged})`
+}
+
export function buildSurveyResponsesExportQuery(
survey: Survey,
filters: SurveyQueryFilters,