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): add response filters to notification setup (#58408)

Lucas Faria04ae1f59d80d
diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
index 8963fa674b12..615ee645ac67 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
@@ -9,6 +9,7 @@ import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/S
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'
import { DESTINATION_OPTIONS } from 'scenes/hog-functions/list/newNotificationDialogLogic'
+import { SurveyResponseFilters } from 'scenes/surveys/components/SurveyResponseFilters'
import { SurveyResponseKeysReference } from 'scenes/surveys/components/SurveyResponseKeysReference'
import {
RESPONDENT_DETAILS_LINE,
@@ -565,6 +566,16 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSX
</>
) : null}
+ <Field name="responseFilters">
+ {({ value, onChange }) => (
+ <SurveyResponseFilters
+ questions={survey.questions}
+ filters={value}
+ onChange={onChange}
+ />
+ )}
+ </Field>
+
<div className="space-y-3">
<div className="border-t border-border" />
<SectionEyebrow>Reference</SectionEyebrow>
diff --git a/frontend/src/scenes/surveys/components/SurveyResponseFilters.tsx b/frontend/src/scenes/surveys/components/SurveyResponseFilters.tsx
new file mode 100644
index 000000000000..c4b6e5611b0c
--- /dev/null
+++ b/frontend/src/scenes/surveys/components/SurveyResponseFilters.tsx
@@ -0,0 +1,327 @@
+import { IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonInputSelect, LemonSelect, Tooltip } from '@posthog/lemon-ui'
+
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
+import { SurveyResponseFilter, defaultResponseFilterForQuestion } from 'scenes/surveys/responseFilters'
+
+import {
+ BasicSurveyQuestion,
+ MultipleSurveyQuestion,
+ RatingSurveyQuestion,
+ SurveyQuestion,
+ SurveyQuestionType,
+} from '~/types'
+
+const RATING_MODE_OPTIONS = [
+ { value: 'lte' as const, label: 'is at most' },
+ { value: 'gte' as const, label: 'is at least' },
+ { value: 'eq' as const, label: 'equals' },
+ { value: 'between' as const, label: 'is between' },
+]
+
+const OPEN_TEXT_MODE_OPTIONS = [
+ { value: 'any' as const, label: 'has any response' },
+ { value: 'contains' as const, label: 'contains' },
+ { value: 'not_contains' as const, label: 'does not contain' },
+]
+
+const SINGLE_CHOICE_MODE_OPTIONS = [
+ { value: 'is_any_of' as const, label: 'is any of' },
+ { value: 'is_none_of' as const, label: 'is none of' },
+]
+
+const MULTIPLE_CHOICE_MODE_OPTIONS = [
+ { value: 'includes_any' as const, label: 'includes any of' },
+ { value: 'includes_none' as const, label: 'includes none of' },
+]
+
+function getQuestionLabel(question: SurveyQuestion, index: number): string {
+ return question.question?.trim() || `Question ${index + 1}`
+}
+
+function isFilterableQuestion(
+ question: SurveyQuestion
+): question is BasicSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion {
+ return question.type !== SurveyQuestionType.Link && !!question.id
+}
+
+function RatingFilterControls({
+ question,
+ filter,
+ onChange,
+}: {
+ question: RatingSurveyQuestion
+ filter: Extract<SurveyResponseFilter, { type: SurveyQuestionType.Rating }>
+ onChange: (next: SurveyResponseFilter) => void
+}): JSX.Element {
+ const minValue = question.scale === 10 ? 0 : 1
+ const maxValue = question.scale
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonSelect
+ size="small"
+ value={filter.mode}
+ onChange={(mode) => onChange({ ...filter, mode })}
+ options={RATING_MODE_OPTIONS}
+ />
+ <LemonInput
+ type="number"
+ size="small"
+ min={minValue}
+ max={maxValue}
+ value={filter.value ?? undefined}
+ onChange={(value) => onChange({ ...filter, value: typeof value === 'number' ? value : null })}
+ className="w-20"
+ />
+ {filter.mode === 'between' ? (
+ <>
+ <span className="text-xs text-muted">and</span>
+ <LemonInput
+ type="number"
+ size="small"
+ min={minValue}
+ max={maxValue}
+ value={filter.upperValue ?? undefined}
+ onChange={(value) =>
+ onChange({ ...filter, upperValue: typeof value === 'number' ? value : null })
+ }
+ className="w-20"
+ />
+ </>
+ ) : null}
+ <span className="text-xs text-muted">
+ (scale {minValue}–{maxValue})
+ </span>
+ </div>
+ )
+}
+
+function OpenTextFilterControls({
+ filter,
+ onChange,
+}: {
+ filter: Extract<SurveyResponseFilter, { type: SurveyQuestionType.Open }>
+ onChange: (next: SurveyResponseFilter) => void
+}): JSX.Element {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonSelect
+ size="small"
+ value={filter.mode}
+ onChange={(mode) => {
+ if (mode === 'any') {
+ onChange({ ...filter, mode, value: '' })
+ } else {
+ onChange({ ...filter, mode })
+ }
+ }}
+ options={OPEN_TEXT_MODE_OPTIONS}
+ />
+ {filter.mode !== 'any' ? (
+ <LemonInput
+ size="small"
+ value={filter.value}
+ onChange={(value) => onChange({ ...filter, value })}
+ placeholder="text to match"
+ className="min-w-48"
+ />
+ ) : null}
+ </div>
+ )
+}
+
+function ChoiceFilterControls<
+ T extends Extract<
+ SurveyResponseFilter,
+ { type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice }
+ >,
+>({
+ question,
+ filter,
+ options,
+ onChange,
+}: {
+ question: MultipleSurveyQuestion
+ filter: T
+ options: { value: T['mode']; label: string }[]
+ onChange: (next: SurveyResponseFilter) => void
+}): JSX.Element {
+ const choiceOptions = question.choices.map((choice) => ({ key: choice, label: choice, value: choice }))
+ return (
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <LemonSelect
+ size="small"
+ value={filter.mode}
+ onChange={(mode) => onChange({ ...filter, mode } as SurveyResponseFilter)}
+ options={options}
+ />
+ <div className="flex-1 min-w-48">
+ <LemonInputSelect
+ mode="multiple"
+ size="small"
+ placeholder="Select choices"
+ options={choiceOptions}
+ value={filter.value}
+ onChange={(value) => onChange({ ...filter, value } as SurveyResponseFilter)}
+ />
+ </div>
+ </div>
+ )
+}
+
+function FilterRow({
+ question,
+ questionIndex,
+ filter,
+ onChange,
+ onRemove,
+}: {
+ question: SurveyQuestion
+ questionIndex: number
+ filter: SurveyResponseFilter
+ onChange: (next: SurveyResponseFilter) => void
+ onRemove: () => void
+}): JSX.Element | null {
+ let controls: JSX.Element | null = null
+ if (filter.type === SurveyQuestionType.Rating && question.type === SurveyQuestionType.Rating) {
+ controls = <RatingFilterControls question={question} filter={filter} onChange={onChange} />
+ } else if (filter.type === SurveyQuestionType.Open && question.type === SurveyQuestionType.Open) {
+ controls = <OpenTextFilterControls filter={filter} onChange={onChange} />
+ } else if (filter.type === SurveyQuestionType.SingleChoice && question.type === SurveyQuestionType.SingleChoice) {
+ controls = (
+ <ChoiceFilterControls
+ question={question}
+ filter={filter}
+ options={SINGLE_CHOICE_MODE_OPTIONS}
+ onChange={onChange}
+ />
+ )
+ } else if (
+ filter.type === SurveyQuestionType.MultipleChoice &&
+ question.type === SurveyQuestionType.MultipleChoice
+ ) {
+ controls = (
+ <ChoiceFilterControls
+ question={question}
+ filter={filter}
+ options={MULTIPLE_CHOICE_MODE_OPTIONS}
+ onChange={onChange}
+ />
+ )
+ }
+
+ if (!controls) {
+ return null
+ }
+
+ return (
+ <div className="rounded border border-border bg-bg-light px-3 py-2 space-y-2">
+ <div className="flex items-start justify-between gap-2">
+ <div className="text-xs font-medium text-default break-words">
+ {getQuestionLabel(question, questionIndex)}
+ </div>
+ <Tooltip title="Remove filter">
+ <LemonButton size="xsmall" type="tertiary" icon={<IconTrash />} onClick={onRemove} />
+ </Tooltip>
+ </div>
+ {controls}
+ </div>
+ )
+}
+
+export function SurveyResponseFilters({
+ questions,
+ filters,
+ onChange,
+}: {
+ questions: SurveyQuestion[]
+ filters: SurveyResponseFilter[]
+ onChange: (next: SurveyResponseFilter[]) => void
+}): JSX.Element | null {
+ const filterableQuestions = questions.filter(isFilterableQuestion)
+ if (filterableQuestions.length === 0) {
+ return null
+ }
+
+ const questionById = new Map<string, { question: SurveyQuestion; index: number }>()
+ questions.forEach((question, index) => {
+ if (question.id) {
+ questionById.set(question.id, { question, index })
+ }
+ })
+
+ const usedQuestionIds = new Set(filters.map((filter) => filter.questionId))
+ const availableQuestions = filterableQuestions.filter(
+ (question) => question.id && !usedQuestionIds.has(question.id)
+ )
+
+ const addFilterFor = (question: SurveyQuestion): void => {
+ const next = defaultResponseFilterForQuestion(question)
+ if (!next) {
+ return
+ }
+ onChange([...filters, next])
+ }
+
+ const updateFilter = (index: number, next: SurveyResponseFilter): void => {
+ const updated = [...filters]
+ updated[index] = next
+ onChange(updated)
+ }
+
+ const removeFilter = (index: number): void => {
+ onChange(filters.filter((_, i) => i !== index))
+ }
+
+ return (
+ <div className="space-y-3">
+ <div className="border-t border-border" />
+ <div className="space-y-1">
+ <div className="text-sm font-medium text-default">Only notify when…</div>
+ <div className="text-xs text-muted">
+ Quiet down noisy notifications by filtering on response content. Filters apply to completed
+ responses only and are combined with AND.
+ </div>
+ </div>
+
+ {filters.length > 0 ? (
+ <div className="space-y-2">
+ {filters.map((filter, index) => {
+ const entry = questionById.get(filter.questionId)
+ if (!entry) {
+ return null
+ }
+ return (
+ <FilterRow
+ key={`${filter.questionId}-${index}`}
+ question={entry.question}
+ questionIndex={entry.index}
+ filter={filter}
+ onChange={(next) => updateFilter(index, next)}
+ onRemove={() => removeFilter(index)}
+ />
+ )
+ })}
+ </div>
+ ) : null}
+
+ {availableQuestions.length > 0 ? (
+ <LemonMenu
+ items={availableQuestions.map((question) => {
+ const index = questionById.get(question.id!)?.index ?? 0
+ return {
+ label: getQuestionLabel(question, index),
+ onClick: () => addFilterFor(question),
+ }
+ })}
+ >
+ <LemonButton size="small" type="secondary" icon={<IconPlus />}>
+ Add response filter
+ </LemonButton>
+ </LemonMenu>
+ ) : (
+ <div className="text-xs text-muted">All eligible questions already have a filter.</div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/surveys/responseFilters.ts b/frontend/src/scenes/surveys/responseFilters.ts
new file mode 100644
index 000000000000..9840706d7b16
--- /dev/null
+++ b/frontend/src/scenes/surveys/responseFilters.ts
@@ -0,0 +1,324 @@
+import { getSurveyIdBasedResponseKey } from 'scenes/surveys/utils'
+
+import {
+ EventPropertyFilter,
+ PropertyFilterType,
+ PropertyOperator,
+ SurveyEventProperties,
+ SurveyQuestion,
+ SurveyQuestionType,
+} from '~/types'
+
+export type RatingFilterMode = 'gte' | 'lte' | 'eq' | 'between'
+export type OpenTextFilterMode = 'any' | 'contains' | 'not_contains'
+export type SingleChoiceFilterMode = 'is_any_of' | 'is_none_of'
+export type MultipleChoiceFilterMode = 'includes_any' | 'includes_none'
+
+export type SurveyResponseFilter =
+ | {
+ questionId: string
+ type: SurveyQuestionType.Rating
+ mode: RatingFilterMode
+ value: number | null
+ upperValue?: number | null
+ }
+ | {
+ questionId: string
+ type: SurveyQuestionType.Open
+ mode: OpenTextFilterMode
+ value: string
+ }
+ | {
+ questionId: string
+ type: SurveyQuestionType.SingleChoice
+ mode: SingleChoiceFilterMode
+ value: string[]
+ }
+ | {
+ questionId: string
+ type: SurveyQuestionType.MultipleChoice
+ mode: MultipleChoiceFilterMode
+ value: string[]
+ }
+
+const RATING_OPERATOR_BY_MODE: Record<Exclude<RatingFilterMode, 'between'>, PropertyOperator> = {
+ gte: PropertyOperator.GreaterThanOrEqual,
+ lte: PropertyOperator.LessThanOrEqual,
+ eq: PropertyOperator.Exact,
+}
+
+const OPEN_TEXT_OPERATOR_BY_MODE: Record<Exclude<OpenTextFilterMode, 'any'>, PropertyOperator> = {
+ contains: PropertyOperator.IContains,
+ not_contains: PropertyOperator.NotIContains,
+}
+
+const SINGLE_CHOICE_OPERATOR_BY_MODE: Record<SingleChoiceFilterMode, PropertyOperator> = {
+ is_any_of: PropertyOperator.Exact,
+ is_none_of: PropertyOperator.IsNot,
+}
+
+const MULTIPLE_CHOICE_OPERATOR_BY_MODE: Record<MultipleChoiceFilterMode, PropertyOperator> = {
+ includes_any: PropertyOperator.IContains,
+ includes_none: PropertyOperator.NotIContains,
+}
+
+export function isSurveyResponsePropertyKey(key: string | null | undefined): boolean {
+ return typeof key === 'string' && key.startsWith(`${SurveyEventProperties.SURVEY_RESPONSE}_`)
+}
+
+export function isResponseFilterValid(filter: SurveyResponseFilter): boolean {
+ switch (filter.type) {
+ case SurveyQuestionType.Rating: {
+ if (filter.mode === 'between') {
+ return (
+ typeof filter.value === 'number' &&
+ typeof filter.upperValue === 'number' &&
+ filter.value <= filter.upperValue
+ )
+ }
+ return typeof filter.value === 'number'
+ }
+ case SurveyQuestionType.Open:
+ return filter.mode === 'any' ? true : filter.value.trim().length > 0
+ case SurveyQuestionType.SingleChoice:
+ case SurveyQuestionType.MultipleChoice:
+ return filter.value.length > 0
+ }
+}
+
+export function defaultResponseFilterForQuestion(question: SurveyQuestion): SurveyResponseFilter | null {
+ if (!question.id) {
+ return null
+ }
+ switch (question.type) {
+ case SurveyQuestionType.Rating:
+ return { questionId: question.id, type: question.type, mode: 'lte', value: null }
+ case SurveyQuestionType.Open:
+ return { questionId: question.id, type: question.type, mode: 'any', value: '' }
+ case SurveyQuestionType.SingleChoice:
+ return { questionId: question.id, type: question.type, mode: 'is_any_of', value: [] }
+ case SurveyQuestionType.MultipleChoice:
+ return { questionId: question.id, type: question.type, mode: 'includes_any', value: [] }
+ case SurveyQuestionType.Link:
+ return null
+ }
+}
+
+function buildEventPropertyFilters(filter: SurveyResponseFilter): EventPropertyFilter[] {
+ const key = getSurveyIdBasedResponseKey(filter.questionId)
+ const base = { key, type: PropertyFilterType.Event } as const
+
+ switch (filter.type) {
+ case SurveyQuestionType.Rating: {
+ if (filter.value === null || filter.value === undefined) {
+ return []
+ }
+ if (filter.mode === 'between') {
+ if (filter.upperValue === null || filter.upperValue === undefined) {
+ return []
+ }
+ return [
+ { ...base, operator: PropertyOperator.GreaterThanOrEqual, value: filter.value },
+ { ...base, operator: PropertyOperator.LessThanOrEqual, value: filter.upperValue },
+ ]
+ }
+ return [{ ...base, operator: RATING_OPERATOR_BY_MODE[filter.mode], value: filter.value }]
+ }
+ case SurveyQuestionType.Open: {
+ if (filter.mode === 'any') {
+ return [{ ...base, operator: PropertyOperator.IsSet, value: PropertyOperator.IsSet }]
+ }
+ const trimmed = filter.value.trim()
+ if (!trimmed) {
+ return []
+ }
+ return [{ ...base, operator: OPEN_TEXT_OPERATOR_BY_MODE[filter.mode], value: trimmed }]
+ }
+ case SurveyQuestionType.SingleChoice: {
+ if (filter.value.length === 0) {
+ return []
+ }
+ return [{ ...base, operator: SINGLE_CHOICE_OPERATOR_BY_MODE[filter.mode], value: filter.value }]
+ }
+ case SurveyQuestionType.MultipleChoice: {
+ if (filter.value.length === 0) {
+ return []
+ }
+ return [{ ...base, operator: MULTIPLE_CHOICE_OPERATOR_BY_MODE[filter.mode], value: filter.value }]
+ }
+ }
+}
+
+export function buildResponseFilterProperties(filters: SurveyResponseFilter[]): EventPropertyFilter[] {
+ return filters.filter(isResponseFilterValid).flatMap(buildEventPropertyFilters)
+}
+
+function findQuestionByResponseKey(
+ key: string | null | undefined,
+ questions: SurveyQuestion[]
+): SurveyQuestion | undefined {
+ if (typeof key !== 'string') {
+ return undefined
+ }
+ return questions.find((question) => question.id && getSurveyIdBasedResponseKey(question.id) === key)
+}
+
+function toFiniteNumber(value: unknown): number | null {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value
+ }
+ if (typeof value === 'string' && value.trim() !== '') {
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : null
+ }
+ return null
+}
+
+function toStringArray(value: unknown): string[] {
+ if (Array.isArray(value)) {
+ return value.filter((v): v is string => typeof v === 'string' && v.length > 0)
+ }
+ if (typeof value === 'string' && value.length > 0) {
+ return [value]
+ }
+ return []
+}
+
+export function parseResponseFiltersFromProperties(
+ properties: EventPropertyFilter[] | undefined | null,
+ questions: SurveyQuestion[]
+): SurveyResponseFilter[] {
+ if (!properties || properties.length === 0) {
+ return []
+ }
+
+ const parsed: SurveyResponseFilter[] = []
+ const byQuestionId: Record<string, SurveyResponseFilter> = {}
+
+ for (const property of properties) {
+ if (property.type !== PropertyFilterType.Event || !isSurveyResponsePropertyKey(property.key)) {
+ continue
+ }
+ const question = findQuestionByResponseKey(property.key, questions)
+ if (!question?.id) {
+ continue
+ }
+
+ switch (question.type) {
+ case SurveyQuestionType.Rating: {
+ const numeric = toFiniteNumber(property.value)
+ if (numeric === null) {
+ continue
+ }
+ const existing = byQuestionId[question.id]
+ if (existing && existing.type === SurveyQuestionType.Rating) {
+ if (
+ property.operator === PropertyOperator.LessThanOrEqual &&
+ existing.mode === 'gte' &&
+ existing.value !== null &&
+ existing.value !== undefined
+ ) {
+ existing.mode = 'between'
+ existing.upperValue = numeric
+ continue
+ }
+ if (
+ property.operator === PropertyOperator.GreaterThanOrEqual &&
+ existing.mode === 'lte' &&
+ existing.value !== null &&
+ existing.value !== undefined
+ ) {
+ existing.mode = 'between'
+ existing.upperValue = existing.value
+ existing.value = numeric
+ continue
+ }
+ }
+ let mode: RatingFilterMode = 'eq'
+ if (property.operator === PropertyOperator.GreaterThanOrEqual) {
+ mode = 'gte'
+ } else if (property.operator === PropertyOperator.LessThanOrEqual) {
+ mode = 'lte'
+ }
+ const entry: SurveyResponseFilter = {
+ questionId: question.id,
+ type: SurveyQuestionType.Rating,
+ mode,
+ value: numeric,
+ }
+ byQuestionId[question.id] = entry
+ parsed.push(entry)
+ break
+ }
+ case SurveyQuestionType.Open: {
+ if (property.operator === PropertyOperator.IsSet) {
+ const entry: SurveyResponseFilter = {
+ questionId: question.id,
+ type: SurveyQuestionType.Open,
+ mode: 'any',
+ value: '',
+ }
+ byQuestionId[question.id] = entry
+ parsed.push(entry)
+ break
+ }
+ if (
+ property.operator === PropertyOperator.IContains ||
+ property.operator === PropertyOperator.NotIContains
+ ) {
+ const text = typeof property.value === 'string' ? property.value : ''
+ const entry: SurveyResponseFilter = {
+ questionId: question.id,
+ type: SurveyQuestionType.Open,
+ mode: property.operator === PropertyOperator.IContains ? 'contains' : 'not_contains',
+ value: text,
+ }
+ byQuestionId[question.id] = entry
+ parsed.push(entry)
+ }
+ break
+ }
+ case SurveyQuestionType.SingleChoice: {
+ const values = toStringArray(property.value)
+ if (values.length === 0) {
+ continue
+ }
+ const entry: SurveyResponseFilter = {
+ questionId: question.id,
+ type: SurveyQuestionType.SingleChoice,
+ mode: property.operator === PropertyOperator.IsNot ? 'is_none_of' : 'is_any_of',
+ value: values,
+ }
+ byQuestionId[question.id] = entry
+ parsed.push(entry)
+ break
+ }
+ case SurveyQuestionType.MultipleChoice: {
+ const values = toStringArray(property.value)
+ if (values.length === 0) {
+ continue
+ }
+ const entry: SurveyResponseFilter = {
+ questionId: question.id,
+ type: SurveyQuestionType.MultipleChoice,
+ mode: property.operator === PropertyOperator.NotIContains ? 'includes_none' : 'includes_any',
+ value: values,
+ }
+ byQuestionId[question.id] = entry
+ parsed.push(entry)
+ break
+ }
+ }
+ }
+
+ return parsed
+}
+
+export function stripResponseFiltersFromProperties(
+ properties: EventPropertyFilter[] | undefined | null
+): EventPropertyFilter[] {
+ if (!properties) {
+ return []
+ }
+ return properties.filter((property) => !isSurveyResponsePropertyKey(property.key))
+}
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
index bdd58b683e40..33ddcecad2e5 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
@@ -14,6 +14,12 @@ import {
HOG_FUNCTION_SUB_TEMPLATES,
} from 'scenes/hog-functions/sub-templates/sub-templates'
import { NEW_SURVEY } from 'scenes/surveys/constants'
+import {
+ SurveyResponseFilter,
+ buildResponseFilterProperties,
+ parseResponseFiltersFromProperties,
+ stripResponseFiltersFromProperties,
+} from 'scenes/surveys/responseFilters'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import {
buildSurveyExampleInvocationGlobals,
@@ -27,6 +33,7 @@ import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'
import {
CyclotronJobInvocationGlobals,
CyclotronJobTestInvocationResult,
+ EventPropertyFilter,
EventType,
HogFunctionTemplateType,
HogFunctionType,
@@ -69,6 +76,7 @@ export interface SurveyNotificationForm {
webhookUrl: string
webhookMethod: string
webhookBody: string
+ responseFilters: SurveyResponseFilter[]
}
export interface SurveyNotificationModalLogicProps {
@@ -84,7 +92,7 @@ export type OpenSurveyNotificationDialogPayload = {
intent?: SurveyNotificationModalIntent
}
type SurveyNotificationContext = Pick<Survey, 'id' | 'name' | 'questions' | 'enable_partial_responses'>
-type SurveyNotificationFormErrors = Partial<Record<keyof SurveyNotificationForm, string>>
+type SurveyNotificationFormErrors = Partial<Record<Exclude<keyof SurveyNotificationForm, 'responseFilters'>, string>>
const MAX_EXAMPLE_QUESTIONS = 3
export const SURVEY_NAME_TOKEN = "{event.properties['$survey_name']}"
@@ -231,6 +239,7 @@ function buildSurveyNotificationForm(survey: SurveyNotificationContext): SurveyN
webhookUrl: '',
webhookMethod: 'POST',
webhookBody: JSON.stringify(buildWebhookBodyTemplate(survey.questions), null, 2),
+ responseFilters: [],
}
}
@@ -529,6 +538,18 @@ function getSlackIncludeButtons(notification: HogFunctionType): boolean {
: false
}
+function getSentEventPropertiesFromNotification(notification: HogFunctionType): EventPropertyFilter[] {
+ const sentEvent = notification.filters?.events?.find((event) => event.id === SurveyEventName.SENT)
+ const properties = sentEvent?.properties ?? []
+ return properties.filter(
+ (property): property is EventPropertyFilter =>
+ typeof property === 'object' &&
+ property !== null &&
+ 'type' in property &&
+ (property as { type?: unknown }).type === PropertyFilterType.Event
+ )
+}
+
function buildSurveyNotificationFormFromNotification(
notification: HogFunctionType,
survey: SurveyNotificationContext,
@@ -540,6 +561,9 @@ function buildSurveyNotificationFormFromNotification(
? remapSurveyResponseProperties(notification.inputs, survey)
: notification.inputs
const remappedNotification = { ...notification, inputs: remappedInputs }
+ const responseFilters = remapResponses
+ ? []
+ : parseResponseFiltersFromProperties(getSentEventPropertiesFromNotification(notification), survey.questions)
return {
...defaults,
@@ -559,6 +583,7 @@ function buildSurveyNotificationFormFromNotification(
null,
2
),
+ responseFilters,
}
}
@@ -643,13 +668,44 @@ function createSurveyNotificationPayload({
description: subTemplate?.description ?? `Survey notification for ${destinationOption.label}`,
inputs,
inputs_schema: template.inputs_schema,
- filters: getSurveyNotificationFilters(surveyId),
+ filters: getSurveyNotificationFilters(surveyId, buildResponseFilterProperties(form.responseFilters)),
hog: template.code,
icon_url: template.icon_url,
enabled: true,
}
}
+function mergeResponseFiltersIntoExistingFilters(
+ existingFilters: HogFunctionType['filters'],
+ fallbackFilters: HogFunctionType['filters'],
+ responseFilters: SurveyResponseFilter[]
+): HogFunctionType['filters'] {
+ const base = existingFilters ?? fallbackFilters
+ if (!base) {
+ return fallbackFilters
+ }
+ const responseProperties = buildResponseFilterProperties(responseFilters)
+ const events = (base.events ?? []).map((event) => {
+ if (event.id !== SurveyEventName.SENT) {
+ return event
+ }
+ const preservedProperties = stripResponseFiltersFromProperties(
+ (event.properties ?? []).filter(
+ (property): property is EventPropertyFilter =>
+ typeof property === 'object' &&
+ property !== null &&
+ 'type' in property &&
+ (property as { type?: unknown }).type === PropertyFilterType.Event
+ )
+ )
+ return {
+ ...event,
+ properties: [...preservedProperties, ...responseProperties],
+ }
+ })
+ return { ...base, events }
+}
+
function updateSurveyNotificationPayload({
notification,
template,
@@ -684,7 +740,7 @@ function updateSurveyNotificationPayload({
},
mappings: notification.mappings,
masking: notification.masking,
- filters: notification.filters ?? payload.filters,
+ filters: mergeResponseFiltersIntoExistingFilters(notification.filters, payload.filters, form.responseFilters),
hog: notification.hog ?? payload.hog,
icon_url: notification.icon_url ?? payload.icon_url,
}
@@ -733,7 +789,7 @@ function createCopiedSurveyNotificationPayload({
},
mappings: remapSurveyResponseProperties(notification.mappings, survey),
masking: notification.masking,
- filters: getSurveyNotificationFilters(survey.id),
+ filters: getSurveyNotificationFilters(survey.id, buildResponseFilterProperties(form.responseFilters)),
hog: remapSurveyResponseProperties(notification.hog, survey) ?? template.code,
icon_url: notification.icon_url ?? template.icon_url,
enabled: true,
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index f2ef8979f19d..519b3ede0464 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -1156,7 +1156,10 @@ export function getSurveyDisplayConditionsSummary(survey: Survey | NewSurvey): S
return parts
}
-export function getSurveyNotificationFilters(surveyId: string): CyclotronJobFiltersType {
+export function getSurveyNotificationFilters(
+ surveyId: string,
+ extraSentEventProperties: EventPropertyFilter[] = []
+): CyclotronJobFiltersType {
const sentEventProperties: EventPropertyFilter[] = [
{
key: SurveyEventProperties.SURVEY_ID,
@@ -1170,6 +1173,7 @@ export function getSurveyNotificationFilters(surveyId: string): CyclotronJobFilt
value: true,
operator: PropertyOperator.Exact,
},
+ ...extraSentEventProperties,
]
return {