: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
feat(surveys): add test button to survey notifications modal (#58515)
Lucas Faria101eeed56671
diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsxindex d3161ddccacd..8963fa674b12 100644--- a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx+++ b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx@@ -1,8 +1,8 @@import { useActions, useValues } from 'kea'import { Field, Form } from 'kea-forms'-import { IconExternal } from '@posthog/icons'-import { LemonButton, LemonInput, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'+import { IconExternal, IconX } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonMenu, LemonSelect, LemonSwitch, Spinner } from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'@@ -26,7 +26,66 @@ import {} from 'scenes/surveys/surveyNotificationModalLogic'import { urls } from 'scenes/urls'-import { SurveyQuestionType } from '~/types'+import { CyclotronJobTestInvocationResult, SurveyQuestionType } from '~/types'++function TestResultPanel({+ loading,+ result,+ error,+ onClear,+}: {+ loading: boolean+ result: CyclotronJobTestInvocationResult | null+ error: string | null+ onClear: () => void+}): JSX.Element {+ const bannerType: 'info' | 'success' | 'warning' | 'error' = error+ ? 'error'+ : loading+ ? 'info'+ : result?.status === 'success'+ ? 'success'+ : result?.status === 'skipped'+ ? 'warning'+ : 'error'+ const heading = error+ ? error+ : loading+ ? 'Sending test notification...'+ : result?.status === 'success'+ ? 'Test notification sent.'+ : result?.status === 'skipped'+ ? 'Test was skipped — the event did not match the notification filters.'+ : 'Test failed.'++ return (+ <LemonBanner type={bannerType} className="flex flex-col gap-2">+ <div className="flex items-start gap-2">+ <div className="flex flex-1 items-center gap-2">+ {loading ? <Spinner /> : null}+ <span>{heading}</span>+ </div>+ {!loading ? (+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ onClick={onClear}+ tooltip="Clear test result"+ data-attr="survey-notification-clear-test-result"+ />+ ) : null}+ </div>+ {!loading && result?.logs && result.logs.length > 0 ? (+ <details>+ <summary className="cursor-pointer text-xs text-muted">Show logs ({result.logs.length})</summary>+ <pre className="mt-2 max-h-60 overflow-auto whitespace-pre-wrap rounded bg-bg-3000 p-2 text-xs">+ {result.logs.map((log) => `[${log.level}] ${log.timestamp} ${log.message}`).join('\n')}+ </pre>+ </details>+ ) : null}+ </LemonBanner>+ )+}function TemplateEditor({value,@@ -155,8 +214,16 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSXnotificationSubmissionError,editingNotification,copiedNotification,+ testResult,+ testResultLoading,+ testResultError,} = useValues(logic)- const { closeDialog, setNotificationFormValue } = useActions(logic)+ const { closeDialog, setNotificationFormValue, sendTestNotification, clearTestResult } = useActions(logic)+ const testDisabledReason = isNotificationFormSubmitting+ ? 'Saving notification...'+ : testResultLoading+ ? 'Sending test...'+ : submitDisabledReasonconst messageField = getMessageFieldForDestination(notificationForm.destination)const messageFormattingActions =@@ -199,6 +266,29 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSXOpen full editor</LemonButton>) : null}+ <LemonMenu+ items={[+ {+ label: 'With sample data',+ onClick: () => sendTestNotification({ source: 'sample' }),+ },+ {+ label: 'With last response',+ onClick: () => sendTestNotification({ source: 'last_response' }),+ },+ ]}+ placement="top-end"+ >+ <LemonButton+ type="secondary"+ loading={testResultLoading}+ disabledReason={testDisabledReason}+ data-attr="survey-notification-send-test"+ tooltip="Sends a real message to your configured destination."+ >+ Send test+ </LemonButton>+ </LemonMenu><LemonButton type="secondary" onClick={closeDialog}>Cancel</LemonButton>@@ -223,6 +313,15 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSX<div className="text-sm text-danger">{notificationSubmissionError}</div>) : null}+ {testResultLoading || testResult || testResultError ? (+ <TestResultPanel+ loading={testResultLoading}+ result={testResult}+ error={testResultError}+ onClear={clearTestResult}+ />+ ) : null}+<Formlogic={surveyNotificationModalLogic}props={logicProps}diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.tsindex f866dad57066..81d1bafe828d 100644--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts@@ -1,6 +1,13 @@-import { SurveyQuestionType } from '~/types'+import { NEW_SURVEY } from 'scenes/surveys/constants'-import { getDefaultSurveyMessage, remapSurveyResponseProperties } from './surveyNotificationModalLogic'+import { NodeKind } from '~/queries/schema/schema-general'+import { PropertyFilterType, PropertyOperator, SurveyEventProperties, SurveyQuestionType } from '~/types'++import {+ buildLastSurveyResponseQuery,+ getDefaultSurveyMessage,+ remapSurveyResponseProperties,+} from './surveyNotificationModalLogic'describe('surveyNotificationModalLogic', () => {it('includes survey status text in the default notification message', () => {@@ -56,6 +63,33 @@ describe('surveyNotificationModalLogic', () => {})})+ it.each([NEW_SURVEY.id, ''])('returns no query when building a last-response lookup for survey id "%s"', (id) => {+ expect(buildLastSurveyResponseQuery(id)).toBeNull()+ })++ it('builds a last-response events query scoped to the survey, matching sent or dismissed', () => {+ const query = buildLastSurveyResponseQuery('survey-abc')+ expect(query).toMatchObject({+ kind: NodeKind.EventsQuery,+ select: ['*', 'person'],+ limit: 1,+ after: '-90d',+ orderBy: ['timestamp DESC'],+ })+ expect(query?.fixedProperties).toEqual([+ {+ key: SurveyEventProperties.SURVEY_ID,+ type: PropertyFilterType.Event,+ value: 'survey-abc',+ operator: PropertyOperator.Exact,+ },+ {+ type: PropertyFilterType.HogQL,+ key: "event IN ('survey sent', 'survey dismissed')",+ },+ ])+ })+it('removes copied survey response properties that do not have a target question', () => {const copiedInputs = {text: {diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.tsindex 698c87d04f00..bdd58b683e40 100644--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts@@ -1,11 +1,13 @@import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { forms } from 'kea-forms'+import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { convertToHogFunctionInvocationGlobals } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'import { DESTINATION_OPTIONS, DestinationKey } from 'scenes/hog-functions/list/newNotificationDialogLogic'import {HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES,@@ -20,11 +22,20 @@ import {} from 'scenes/surveys/utils'import { urls } from 'scenes/urls'+import { performQuery } from '~/queries/query'+import { EventsQuery, NodeKind } from '~/queries/schema/schema-general'import {+ CyclotronJobInvocationGlobals,+ CyclotronJobTestInvocationResult,+ EventType,HogFunctionTemplateType,HogFunctionType,IntegrationType,+ PersonType,+ PropertyFilterType,+ PropertyOperator,Survey,+ SurveyEventName,SurveyEventProperties,SurveyQuestionType,} from '~/types'@@ -66,6 +77,7 @@ export interface SurveyNotificationModalLogicProps {type SurveyMessageField = 'slackMessage' | 'discordMessage' | 'teamsMessage'type HogFunctionInputValue = HogFunctionType['inputs'] extends Record<string, infer T> | null | undefined ? T : never+export type SurveyNotificationTestSource = 'sample' | 'last_response'export type SurveyNotificationModalIntent = 'add' | 'edit' | 'copy'export type OpenSurveyNotificationDialogPayload = {notification?: HogFunctionType | null@@ -222,7 +234,7 @@ function buildSurveyNotificationForm(survey: SurveyNotificationContext): SurveyN}}-function buildTemplateGlobals(survey: SurveyNotificationContext): Record<string, unknown> {+function buildTemplateGlobals(survey: SurveyNotificationContext): CyclotronJobInvocationGlobals {return buildSurveyExampleInvocationGlobals({survey,projectId: 1,@@ -231,6 +243,130 @@ function buildTemplateGlobals(survey: SurveyNotificationContext): Record<string,})}+export function buildLastSurveyResponseQuery(surveyId: string): EventsQuery | null {+ if (!surveyId || surveyId === NEW_SURVEY.id) {+ return null+ }+ return {+ kind: NodeKind.EventsQuery,+ select: ['*', 'person'],+ fixedProperties: [+ {+ key: SurveyEventProperties.SURVEY_ID,+ type: PropertyFilterType.Event,+ value: surveyId,+ operator: PropertyOperator.Exact,+ },+ {+ type: PropertyFilterType.HogQL,+ key: `event IN ('${SurveyEventName.SENT}', '${SurveyEventName.DISMISSED}')`,+ },+ ],+ after: '-90d',+ orderBy: ['timestamp DESC'],+ limit: 1,+ modifiers: {+ personsOnEventsMode: 'person_id_no_override_properties_on_events',+ },+ }+}++type LastSurveyResponseResult =+ | { status: 'ok'; globals: CyclotronJobInvocationGlobals }+ | { status: 'empty' }+ | { status: 'failed' }++/**+ * Aligns sample globals with the saved notification's first event filter so the test+ * passes the compiled filter bytecode. Without this, a tiny mismatch (e.g. a survey id+ * that drifted from `values.survey.id` due to copying or migration) skips the test.+ */+function alignGlobalsWithNotificationFilter(+ globals: CyclotronJobInvocationGlobals,+ notification: HogFunctionType | null+): CyclotronJobInvocationGlobals {+ const effectiveFilter = notification?.mappings?.[0]?.filters ?? notification?.filters ?? null+ const firstEvent = effectiveFilter?.events?.[0]+ if (!firstEvent) {+ return globals+ }+ const mergedProperties = { ...globals.event.properties }+ for (const prop of firstEvent.properties ?? []) {+ if ('key' in prop && prop.key && 'value' in prop && prop.value !== undefined) {+ mergedProperties[prop.key] = prop.value+ }+ }+ return {+ ...globals,+ event: {+ ...globals.event,+ event: typeof firstEvent.id === 'string' ? firstEvent.id : globals.event.event,+ properties: mergedProperties,+ },+ }+}++async function fetchLastSurveyResponseGlobals(query: EventsQuery | null): Promise<LastSurveyResponseResult> {+ if (!query) {+ return { status: 'empty' }+ }+ try {+ const response = await performQuery(query)+ const row = response?.results?.[0]+ const event = row?.[0] as EventType | undefined+ const person = row?.[1] as PersonType | undefined+ if (!event || !person) {+ return { status: 'empty' }+ }+ return { status: 'ok', globals: convertToHogFunctionInvocationGlobals(event, person) }+ } catch {+ return { status: 'failed' }+ }+}++async function buildSurveyNotificationPayload({+ form,+ survey,+ editingNotification,+ copiedNotification,+}: {+ form: SurveyNotificationForm+ survey: SurveyNotificationContext+ editingNotification: HogFunctionType | null+ copiedNotification: HogFunctionType | null+}): Promise<Partial<HogFunctionType>> {+ const templateId = DESTINATION_OPTIONS.find((option) => option.value === form.destination)?.templateId+ const template = await api.hogFunctions.getTemplate(templateId || 'template-slack')++ if (editingNotification) {+ return updateSurveyNotificationPayload({+ notification: editingNotification,+ template,+ destination: form.destination,+ surveyId: survey.id,+ form,+ })+ }++ if (copiedNotification) {+ return createCopiedSurveyNotificationPayload({+ notification: copiedNotification,+ template,+ destination: form.destination,+ survey,+ form,+ })+ }++ return createSurveyNotificationPayload({+ template,+ destination: form.destination,+ surveyName: survey.name,+ surveyId: survey.id,+ form,+ })+}+function notificationNameFor(destination: DestinationKey, surveyName?: string | null): string {const destinationLabel = DESTINATION_OPTIONS.find((option) => option.value === destination)?.label || 'Notification'const baseName = surveyName?.trim() || 'Survey'@@ -680,6 +816,8 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypesetNotificationSubmissionError: (error: string | null) => ({ error }),setPendingDeepLink: (target: string | null) => ({ target }),consumePendingDeepLink: true,+ clearTestResult: true,+ sendTestNotification: (payload: { source: SurveyNotificationTestSource }) => ({ source: payload.source }),}),reducers({@@ -719,8 +857,67 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypeopenDialog: () => null,},],+ testResultError: [+ null as string | null,+ {+ sendTestNotification: () => null,+ sendTestNotificationSuccess: () => null,+ sendTestNotificationFailure: (_, { error }) => error || 'Failed to send test notification.',+ openDialog: () => null,+ closeDialog: () => null,+ clearTestResult: () => null,+ },+ ],}),+ loaders(({ values }) => ({+ testResult: [+ null as CyclotronJobTestInvocationResult | null,+ {+ clearTestResult: () => null,+ sendTestNotification: async ({ source }) => {+ const configuration = await buildSurveyNotificationPayload({+ form: values.notificationForm,+ survey: values.survey,+ editingNotification: values.editingNotification,+ copiedNotification: values.copiedNotification,+ })++ let globals: CyclotronJobInvocationGlobals = values.templateGlobals+ let usingSample = source === 'sample'+ if (source === 'last_response') {+ const lookup = await fetchLastSurveyResponseGlobals(values.lastResponseEventQuery)+ if (lookup.status === 'ok') {+ globals = lookup.globals+ } else if (lookup.status === 'failed') {+ usingSample = true+ lemonToast.warning(+ 'Could not fetch the last response — sent the test with sample data instead.'+ )+ } else {+ usingSample = true+ lemonToast.info('No survey responses yet — sent the test with sample data instead.')+ }+ }++ // Align sample globals with the saved filter's expected values so the test+ // isn't skipped by a $survey_id or completion-flag mismatch. Applies to an+ // explicit sample-data test and to a last-response test that fell back to it.+ if (usingSample) {+ globals = alignGlobalsWithNotificationFilter(globals, values.editingNotification)+ }++ const id = values.editingNotification?.id ?? 'new'+ return await api.hogFunctions.createTestInvocation(id, {+ configuration: configuration as Record<string, any>,+ mock_async_functions: false,+ globals,+ })+ },+ },+ ],+ })),+forms(({ values }) => ({notificationForm: {defaults: buildSurveyNotificationForm(NEW_SURVEY),@@ -732,32 +929,12 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypefalse) as boolean),submit: async (form: SurveyNotificationForm) => {- const templateId = DESTINATION_OPTIONS.find((option) => option.value === form.destination)?.templateId- const template = await api.hogFunctions.getTemplate(templateId || 'template-slack')-- const payload = values.editingNotification- ? updateSurveyNotificationPayload({- notification: values.editingNotification,- template,- destination: form.destination,- surveyId: values.survey.id,- form,- })- : values.copiedNotification- ? createCopiedSurveyNotificationPayload({- notification: values.copiedNotification,- template,- destination: form.destination,- survey: values.survey,- form,- })- : createSurveyNotificationPayload({- template,- destination: form.destination,- surveyName: values.survey.name,- surveyId: values.survey.id,- form,- })+ const payload = await buildSurveyNotificationPayload({+ form,+ survey: values.survey,+ editingNotification: values.editingNotification,+ copiedNotification: values.copiedNotification,+ })if (values.editingNotification) {await api.hogFunctions.update(values.editingNotification.id, payload)@@ -781,6 +958,10 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypenull,],templateGlobals: [(s) => [s.survey], (survey: SurveyNotificationContext) => buildTemplateGlobals(survey)],+ lastResponseEventQuery: [+ (s) => [s.survey],+ (survey: SurveyNotificationContext): EventsQuery | null => buildLastSurveyResponseQuery(survey.id),+ ],submitDisabledReason: [(s) => [s.survey,@@ -814,12 +995,23 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypelisteners(({ actions, values }) => ({openDialog: ({ notification, intent }) => {actions.resetNotificationForm()+ actions.clearTestResult()actions.setNotificationFormValues(notification? buildSurveyNotificationFormFromNotification(notification, values.survey, intent === 'copy'): buildSurveyNotificationForm(values.survey))},+ sendTestNotificationSuccess: ({ testResult }) => {+ if (testResult?.status === 'success') {+ lemonToast.success('Test notification sent.')+ } else if (testResult?.status === 'error') {+ lemonToast.error('Test notification failed — see logs below.')+ }+ },+ sendTestNotificationFailure: ({ error }) => {+ lemonToast.error(error || 'Failed to send test notification.')+ },setPendingDeepLink: ({ target }) => {if (!target) {return@@ -864,6 +1056,7 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType},closeDialog: () => {actions.resetNotificationForm()+ actions.clearTestResult()// If a deep link arrived while another dialog was already open it stayed pending —// try to consume it now that we're no longer blocked by `isOpen`.if (values.pendingDeepLink) {