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.

fix(workflows): resolve a survey trigger's survey by id (#97043)

ruby childs000fb0e9802a
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts
index 3ebe4768e874..2020f10d9a89 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts
@@ -27,6 +27,8 @@ describe('surveyTriggerLogic', () => {
function useSetupMocks({
surveys = [] as Survey[],
moreSurveys = [] as Survey[],
+ searchResults = [] as Survey[],
+ surveysById = {} as Record<string, Survey>,
responseCounts = {} as Record<string, number>,
listError = false,
moreListError = false,
@@ -38,7 +40,11 @@ describe('surveyTriggerLogic', () => {
if (listError) {
return [500, { detail: 'Server error' }]
}
- const offset = Number(new URL(request.url).searchParams.get('offset') || 0)
+ const params = new URL(request.url).searchParams
+ if (params.get('search')) {
+ return [200, { results: searchResults, count: searchResults.length }]
+ }
+ const offset = Number(params.get('offset') || 0)
if (offset > 0) {
if (moreListError && !loadMoreCalled) {
loadMoreCalled = true
@@ -51,6 +57,10 @@ describe('surveyTriggerLogic', () => {
'/api/projects/:team_id/surveys/responses_count/': () => {
return [200, responseCounts]
},
+ '/api/projects/:team_id/surveys/:id/': ({ params }) => {
+ const survey = surveysById[params.id as string]
+ return survey ? [200, survey] : [404, { detail: 'Not found' }]
+ },
},
})
}
@@ -168,7 +178,7 @@ describe('surveyTriggerLogic', () => {
})
})
- describe('search filtering', () => {
+ describe('search', () => {
it('returns all surveys when search term is empty', async () => {
const surveys = makeSurveys(3)
useSetupMocks({ surveys })
@@ -182,27 +192,28 @@ describe('surveyTriggerLogic', () => {
})
})
- it('filters surveys by name (case-insensitive)', async () => {
- const alpha = makeSurvey({ name: 'Alpha Survey' })
- const beta = makeSurvey({ name: 'Beta Questionnaire' })
- const gamma = makeSurvey({ name: 'gamma survey' })
- useSetupMocks({ surveys: [alpha, beta, gamma] })
+ it('searches server-side so surveys beyond the loaded pages are reachable', async () => {
+ const loaded = makeSurveys(20)
+ const oldSurvey = makeSurvey({ name: 'Quarterly product feedback' })
+ useSetupMocks({ surveys: loaded, searchResults: [oldSurvey] })
logic = surveyTriggerLogic()
logic.mount()
await expectLogic(logic).toDispatchActions(['loadSurveysSuccess'])
await expectLogic(logic, () => {
- logic.actions.setSearchTerm('survey')
- }).toMatchValues({
- searchTerm: 'survey',
- filteredSurveys: [alpha, gamma],
+ logic.actions.setSearchTerm('NPS')
})
+ .toDispatchActions(['searchSurveys', 'searchSurveysSuccess'])
+ .toMatchValues({
+ searchTerm: 'NPS',
+ filteredSurveys: [oldSurvey],
+ })
})
it('returns empty array when no surveys match search', async () => {
const surveys = makeSurveys(3)
- useSetupMocks({ surveys })
+ useSetupMocks({ surveys, searchResults: [] })
logic = surveyTriggerLogic()
logic.mount()
@@ -210,23 +221,28 @@ describe('surveyTriggerLogic', () => {
await expectLogic(logic, () => {
logic.actions.setSearchTerm('nonexistent')
- }).toMatchValues({
- filteredSurveys: [],
})
+ .toDispatchActions(['searchSurveysSuccess'])
+ .toMatchValues({
+ filteredSurveys: [],
+ })
})
- it('resets filtered results when search term is cleared', async () => {
+ it('resets to the loaded surveys when search term is cleared', async () => {
const surveys = makeSurveys(3)
- useSetupMocks({ surveys })
+ const other = makeSurvey({ name: 'Other' })
+ useSetupMocks({ surveys, searchResults: [other] })
logic = surveyTriggerLogic()
logic.mount()
await expectLogic(logic).toDispatchActions(['loadSurveysSuccess'])
- logic.actions.setSearchTerm('Survey 1')
- await expectLogic(logic).toMatchValues({
- filteredSurveys: [surveys[0]],
- })
+ logic.actions.setSearchTerm('Other')
+ await expectLogic(logic)
+ .toDispatchActions(['searchSurveysSuccess'])
+ .toMatchValues({
+ filteredSurveys: [other],
+ })
await expectLogic(logic, () => {
logic.actions.setSearchTerm('')
@@ -236,6 +252,35 @@ describe('surveyTriggerLogic', () => {
})
})
+ describe('resolving a configured survey by id', () => {
+ // A trigger can point at any survey, so the picker has to resolve one outside its loaded pages
+ // and tell "still fetching" apart from "deleted" — the banner and the select label both depend on it.
+ it.each([
+ ['fetches a survey that is not in the loaded pages', true],
+ ['records a null entry when the survey no longer exists', false],
+ ])('%s', async (_name, exists) => {
+ const configured = makeSurvey({ id: 'configured-survey', name: 'Quarterly product feedback' })
+ useSetupMocks({
+ surveys: makeSurveys(20),
+ surveysById: exists ? { 'configured-survey': configured } : {},
+ })
+
+ logic = surveyTriggerLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSurveysSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSurveyById('configured-survey')
+ })
+ .toDispatchActions(['loadSurveyByIdSuccess'])
+ .toMatchValues({
+ selectedSurveys: { 'configured-survey': exists ? configured : null },
+ })
+
+ expect(logic.values.surveysById['configured-survey']).toEqual(exists ? configured : undefined)
+ })
+ })
+
describe('error handling', () => {
beforeEach(silenceKeaLoadersErrors)
afterEach(resumeKeaLoadersErrors)
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.ts
index dbdb00019b94..dc4443134da0 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, kea, listeners, path, props, propsChanged, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
@@ -8,6 +8,14 @@ import api from 'lib/api'
import { Survey } from '~/types'
const SURVEYS_PAGE_SIZE = 20
+const SEARCH_DEBOUNCE_MS = 300
+
+// Not named `surveyTriggerLogicProps`: kea-typegen reserves the `<logic>Props` name for the props
+// type it generates, and `typegen write --delete` removes any hand-written interface using it.
+export interface SurveyTriggerProps {
+ /** The survey the trigger is configured with, so it can be resolved even when it is outside the loaded pages. */
+ selectedSurveyId?: string | null
+}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyTriggerLogicValues {
@@ -19,7 +27,12 @@ export interface surveyTriggerLogicValues {
responseCounts: Record<string, number>
responseCountsLoading: boolean
searchTerm: string
+ searchedSurveys: Survey[]
+ searchedSurveysLoading: boolean
+ selectedSurveys: Record<string, Survey | null>
+ selectedSurveysLoading: boolean
surveys: Survey[]
+ surveysById: Record<string, Survey>
surveysLoading: boolean
}
@@ -59,6 +72,27 @@ export interface surveyTriggerLogicActions {
}
payload?: any
}
+ loadSurveyById: (id: string) => {
+ id: string
+ }
+ loadSurveyByIdFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSurveyByIdSuccess: (
+ selectedSurveys: Record<string, Survey | null>,
+ payload?: {
+ id: string
+ }
+ ) => {
+ selectedSurveys: Record<string, Survey | null>
+ payload?: {
+ id: string
+ }
+ }
loadSurveys: () => any
loadSurveysFailure: (
error: string,
@@ -74,6 +108,21 @@ export interface surveyTriggerLogicActions {
surveys: Survey[]
payload?: any
}
+ searchSurveys: (searchTerm: string) => string
+ searchSurveysFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ searchSurveysSuccess: (
+ searchedSurveys: Survey[],
+ payload?: string
+ ) => {
+ searchedSurveys: Survey[]
+ payload?: string
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -82,21 +131,28 @@ export interface surveyTriggerLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyTriggerLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- filteredSurveys: (allSurveys: Survey[], searchTerm: string) => Survey[]
+ filteredSurveys: (allSurveys: Survey[], searchedSurveys: Survey[], searchTerm: string) => Survey[]
+ surveysById: (
+ allSurveys: Survey[],
+ searchedSurveys: Survey[],
+ selectedSurveys: Record<string, Survey | null>
+ ) => Record<string, Survey>
}
}
export type surveyTriggerLogicType = MakeLogicType<
surveyTriggerLogicValues,
surveyTriggerLogicActions,
- Record<string, any>,
+ SurveyTriggerProps,
surveyTriggerLogicMeta
>
export const surveyTriggerLogic = kea<surveyTriggerLogicType>([
path(['products', 'workflows', 'frontend', 'Workflows', 'hogflows', 'registry', 'triggers', 'surveyTriggerLogic']),
+ props({} as SurveyTriggerProps),
actions({
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
+ loadSurveyById: (id: string) => ({ id }),
}),
loaders(({ values }) => ({
surveys: [
@@ -121,11 +177,51 @@ export const surveyTriggerLogic = kea<surveyTriggerLogicType>([
},
},
],
+ // Search runs server-side: a project can hold hundreds of surveys, so filtering only the
+ // pages already loaded hides most of them from the picker.
+ searchedSurveys: [
+ [] as Survey[],
+ {
+ searchSurveys: async (searchTerm: string, breakpoint) => {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ const search = searchTerm
+ if (!search) {
+ return []
+ }
+ const response = await api.surveys.list({
+ limit: SURVEYS_PAGE_SIZE,
+ archived: false,
+ search,
+ })
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
+ // A trigger can point at any survey, including one far outside the first page — fetch it by
+ // id so an already-configured trigger renders its survey instead of looking unset.
+ // A null entry means the fetch resolved but the survey is gone.
+ selectedSurveys: [
+ {} as Record<string, Survey | null>,
+ {
+ loadSurveyById: async ({ id }) => {
+ if (id in values.selectedSurveys) {
+ return values.selectedSurveys
+ }
+ try {
+ const survey = await api.surveys.get(id)
+ return { ...values.selectedSurveys, [id]: survey }
+ } catch {
+ return { ...values.selectedSurveys, [id]: null }
+ }
+ },
+ },
+ ],
responseCounts: [
{} as Record<string, number>,
{
loadResponseCounts: async () => {
- const surveyIds = values.allSurveys.map((s) => s.id).join(',')
+ const surveyIds = Object.keys(values.surveysById).join(',')
if (!surveyIds) {
return {}
}
@@ -158,32 +254,66 @@ export const surveyTriggerLogic = kea<surveyTriggerLogicType>([
}),
selectors({
filteredSurveys: [
- (s) => [s.allSurveys, s.searchTerm],
- (allSurveys: Survey[], searchTerm: string): Survey[] => {
- if (!searchTerm) {
- return allSurveys
+ (s) => [s.allSurveys, s.searchedSurveys, s.searchTerm],
+ (allSurveys: Survey[], searchedSurveys: Survey[], searchTerm: string): Survey[] =>
+ searchTerm ? searchedSurveys : allSurveys,
+ ],
+ surveysById: [
+ (s) => [s.allSurveys, s.searchedSurveys, s.selectedSurveys],
+ (
+ allSurveys: Survey[],
+ searchedSurveys: Survey[],
+ selectedSurveys: Record<string, Survey | null>
+ ): Record<string, Survey> => {
+ const byId: Record<string, Survey> = {}
+ for (const survey of [...allSurveys, ...searchedSurveys]) {
+ byId[survey.id] = survey
+ }
+ for (const survey of Object.values(selectedSurveys)) {
+ if (survey) {
+ byId[survey.id] = survey
+ }
}
- const lower = searchTerm.toLowerCase()
- return allSurveys.filter((s) => s.name.toLowerCase().includes(lower))
+ return byId
},
],
}),
- afterMount(({ actions }) => {
+ afterMount(({ actions, props }) => {
actions.loadSurveys()
+ if (props.selectedSurveyId) {
+ actions.loadSurveyById(props.selectedSurveyId)
+ }
+ }),
+ propsChanged(({ actions, props }, oldProps) => {
+ if (props.selectedSurveyId && props.selectedSurveyId !== oldProps.selectedSurveyId) {
+ actions.loadSurveyById(props.selectedSurveyId)
+ }
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
+ setSearchTerm: () => {
+ actions.searchSurveys(values.searchTerm)
+ },
loadSurveysSuccess: () => {
actions.loadResponseCounts()
},
loadMoreSurveysSuccess: () => {
actions.loadResponseCounts()
},
+ searchSurveysSuccess: () => {
+ actions.loadResponseCounts()
+ },
+ loadSurveyByIdSuccess: () => {
+ actions.loadResponseCounts()
+ },
loadSurveysFailure: ({ error }) => {
lemonToast.error('Failed to load surveys: ' + error)
},
loadMoreSurveysFailure: ({ error }) => {
lemonToast.error('Failed to load more surveys: ' + error)
},
+ searchSurveysFailure: ({ error }) => {
+ lemonToast.error('Failed to search surveys: ' + error)
+ },
loadResponseCountsFailure: ({ error }) => {
lemonToast.error('Failed to load response counts: ' + error)
},
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx
index 3898d87bc4f4..a8838344ec10 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveys.tsx
@@ -90,17 +90,23 @@ export function buildProperties(
function StepTriggerConfigurationSurvey({ node }: { node: any }): JSX.Element {
const { setWorkflowActionConfig } = useActions(workflowLogic)
const config = node.data.config as EventTriggerConfig
+ const selectedSurveyId = getSelectedSurveyId(config)
+ const triggerLogic = surveyTriggerLogic({
+ selectedSurveyId: selectedSurveyId === 'any' ? null : selectedSurveyId,
+ })
const {
allSurveys,
filteredSurveys,
+ surveysById,
+ selectedSurveys,
searchTerm,
surveysLoading,
+ searchedSurveysLoading,
moreSurveysLoading,
hasMoreSurveys,
responseCounts,
- } = useValues(surveyTriggerLogic)
- const { loadMoreSurveys, setSearchTerm } = useActions(surveyTriggerLogic)
- const selectedSurveyId = getSelectedSurveyId(config)
+ } = useValues(triggerLogic)
+ const { loadMoreSurveys, setSearchTerm } = useActions(triggerLogic)
const completedOnly = getCompletedResponsesOnly(config)
const userProperties = getUserProperties(config)
const filterTestAccounts = config.filters?.filter_test_accounts ?? false
@@ -120,10 +126,11 @@ function StepTriggerConfigurationSurvey({ node }: { node: any }): JSX.Element {
})
}
- const selectedSurvey =
- selectedSurveyId && selectedSurveyId !== 'any' ? allSurveys.find((s) => s.id === selectedSurveyId) : null
+ const hasSpecificSurvey = !!selectedSurveyId && selectedSurveyId !== 'any'
+ const selectedSurvey = hasSpecificSurvey ? (surveysById[selectedSurveyId] ?? null) : null
+ const selectedSurveyMissing = hasSpecificSurvey && selectedSurveys[selectedSurveyId] === null
const selectedSurveyLabel =
- selectedSurvey?.name ?? (selectedSurveyId && selectedSurveyId !== 'any' ? 'Loading...' : null)
+ selectedSurvey?.name ?? (hasSpecificSurvey ? (selectedSurveyMissing ? 'Survey not found' : 'Loading...') : null)
const surveyOptions = [
...(selectedSurveyId && selectedSurveyLabel
@@ -226,7 +233,7 @@ function StepTriggerConfigurationSurvey({ node }: { node: any }): JSX.Element {
<LemonSelect
options={surveyOptions}
value={selectedSurveyId}
- loading={surveysLoading}
+ loading={surveysLoading || searchedSurveysLoading}
onChange={(surveyId) => {
if (surveyId === '__search__') {
return
@@ -282,7 +289,7 @@ function StepTriggerConfigurationSurvey({ node }: { node: any }): JSX.Element {
)
}
- if (selectedSurveyId && selectedSurveyId !== 'any' && !surveysLoading && !selectedSurvey) {
+ if (selectedSurveyMissing) {
return (
<LemonBanner type="warning" className="w-full">
<p>