: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): unify list-page notifications tab with per-survey UI (#58513)
Lucas Fariaf2d2ca5acf20
diff --git a/frontend/src/scenes/surveys/Surveys.tsx b/frontend/src/scenes/surveys/Surveys.tsxindex f78e1315146a..adab69b1ec67 100644--- a/frontend/src/scenes/surveys/Surveys.tsx+++ b/frontend/src/scenes/surveys/Surveys.tsx@@ -7,17 +7,17 @@ import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'-import { LinkedHogFunctions } from 'scenes/hog-functions/list/LinkedHogFunctions'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'import { SurveyFeedbackButton } from 'scenes/surveys/components/SurveyFeedbackButton'+import { SurveyNotificationsList } from 'scenes/surveys/components/SurveyNotificationsList'import { SurveysTable } from 'scenes/surveys/components/SurveysTable'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'-import { AccessControlLevel, AccessControlResourceType, ActivityScope, SurveyEventName } from '~/types'+import { AccessControlLevel, AccessControlResourceType, ActivityScope } from '~/types'import { SURVEY_CREATED_SOURCE } from './constants'import { DuplicateToProjectModal } from './DuplicateToProjectModal'@@ -110,14 +110,13 @@ function Surveys(): JSX.Element {/>{tab === SurveysTabs.Settings && <SurveySettings />}{tab === SurveysTabs.Notifications && (- <>- <p>Get notified whenever a survey result is submitted</p>- <LinkedHogFunctions- type="destination"- subTemplateIds={['survey-response']}- forceFilterGroups={[{ events: [{ id: SurveyEventName.SENT, type: 'events' }] }]}- />- </>+ <div className="flex flex-col gap-3">+ <p className="m-0 text-sm text-muted">+ Get notified whenever a survey result is submitted. Open a survey to add or edit its+ notifications.+ </p>+ <SurveyNotificationsList />+ </div>)}{tab === SurveysTabs.History && <ActivityLog scope={ActivityScope.SURVEY} />}diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsxnew file mode 100644index 000000000000..f6cc07263dd1--- /dev/null+++ b/frontend/src/scenes/surveys/components/SurveyNotificationsList.tsx@@ -0,0 +1,172 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { LemonBanner, LemonButton, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'++import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'+import {+ getSurveyIdsFromNotificationFilters,+ surveyNotificationsListLogic,+} from 'scenes/surveys/surveyNotificationsListLogic'+import { urls } from 'scenes/urls'++import { HogFunctionType, Survey } from '~/types'++function getNotificationDescription(fn: HogFunctionType): string | null {+ const inputs = fn.inputs+ if (!inputs) {+ return null+ }+ if (inputs.url?.value) {+ try {+ return new URL(String(inputs.url.value)).hostname+ } catch {+ return String(inputs.url.value)+ }+ }+ if (inputs.channel?.value) {+ return String(inputs.channel.value)+ }+ if (inputs.email?.value) {+ return String(inputs.email.value)+ }+ return null+}++function surveyNotificationsUrl(surveyId: string, params: Record<string, string> = {}): string {+ const search = new URLSearchParams({ tab: 'notifications', ...params }).toString()+ return `${urls.survey(surveyId)}?${search}`+}++function NewNotificationPicker(): JSX.Element {+ const { push } = useActions(router)+ const { selectableSurveys, knownSurveysLoading } = useValues(surveyNotificationsListLogic)++ const options = selectableSurveys.map((survey: Pick<Survey, 'id' | 'name'>) => ({+ key: survey.id,+ label: survey.name,+ }))++ const handleChange = (newValue: string[]): void => {+ const surveyId = newValue[0]+ if (surveyId) {+ push(surveyNotificationsUrl(surveyId, { notification: 'add' }))+ }+ }++ return (+ <div className="w-80 max-w-full">+ <LemonInputSelect+ mode="single"+ placeholder="Add notification to a survey…"+ title="Add notification to…"+ options={options}+ value={null}+ onChange={handleChange}+ loading={knownSurveysLoading}+ size="small"+ emptyStateComponent={+ <div className="p-2 text-xs text-muted">No surveys to notify on. Create a survey first.</div>+ }+ data-attr="survey-list-new-notification-picker"+ />+ </div>+ )+}++export function SurveyNotificationsList(): JSX.Element {+ const { notifications, notificationsLoading, notificationsFailed, knownSurveysFailed } =+ useValues(surveyNotificationsListLogic)+ const { toggleNotificationEnabled, loadNotifications, loadKnownSurveys } = useActions(surveyNotificationsListLogic)+ const { push } = useActions(router)++ if (notificationsLoading) {+ return (+ <div className="flex flex-col gap-2">+ <LemonSkeleton className="h-12" />+ <LemonSkeleton className="h-12" />+ <LemonSkeleton className="h-12" />+ </div>+ )+ }++ if (notificationsFailed) {+ return (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => loadNotifications() }}+ data-attr="survey-notifications-load-error"+ >+ We couldn't load your survey notifications. Please try again in a moment.+ </LemonBanner>+ )+ }++ if (notifications.length === 0) {+ return (+ <div className="flex flex-col items-center gap-3 rounded border border-dashed p-6 text-center">+ <div className="space-y-1">+ <p className="m-0 text-sm font-medium">No survey notifications yet</p>+ <p className="m-0 text-xs text-muted">+ Send every new survey response to Slack, Discord, Microsoft Teams, or a webhook.+ </p>+ </div>+ <NewNotificationPicker />+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-3">+ {knownSurveysFailed ? (+ <LemonBanner+ type="warning"+ action={{ children: 'Retry', onClick: () => loadKnownSurveys() }}+ data-attr="survey-notifications-known-surveys-error"+ >+ We couldn't verify which surveys still exist, so notifications for deleted surveys may appear here.+ </LemonBanner>+ ) : null}+ <div className="flex flex-col gap-1.5">+ {notifications.map((fn) => {+ const description = getNotificationDescription(fn)+ const surveyId = getSurveyIdsFromNotificationFilters(fn.filters)[0] ?? null++ const handleEdit = (): void => {+ if (surveyId) {+ push(surveyNotificationsUrl(surveyId, { notification: fn.id }))+ }+ }++ return (+ <div key={fn.id} className="flex items-center gap-2 rounded border p-2">+ <HogFunctionIcon src={fn.icon_url} size="small" />+ <div className="flex-1 min-w-0">+ <LemonButton+ type="tertiary"+ size="xsmall"+ onClick={handleEdit}+ disabledReason={+ surveyId ? undefined : 'This notification is not linked to a survey.'+ }+ className="font-medium p-0 h-auto min-h-0"+ noPadding+ >+ <span className="truncate">{fn.name}</span>+ </LemonButton>+ {description ? <div className="text-xs text-muted truncate">{description}</div> : null}+ </div>+ <LemonSwitch+ checked={fn.enabled}+ onChange={() => toggleNotificationEnabled(fn.id, !fn.enabled)}+ size="small"+ />+ </div>+ )+ })}+ </div>+ <NewNotificationPicker />+ </div>+ )+}diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.tsindex a48d9bc74a2e..698c87d04f00 100644--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts@@ -1,5 +1,6 @@import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { forms } from 'kea-forms'+import { actionToUrl, router, urlToAction } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'@@ -17,6 +18,7 @@ import {getSurveyNotificationFilters,getSurveyIdBasedResponseKey,} from 'scenes/surveys/utils'+import { urls } from 'scenes/urls'import {HogFunctionTemplateType,@@ -657,8 +659,16 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypeprops({} as SurveyNotificationModalLogicProps),key((props) => props.surveyId),connect((props: SurveyNotificationModalLogicProps) => ({- values: [integrationsLogic, ['integrations'], surveyLogic({ id: props.surveyId }), ['survey']],- actions: [surveyLogic({ id: props.surveyId }), ['loadSurveyNotifications']],+ values: [+ integrationsLogic,+ ['integrations'],+ surveyLogic({ id: props.surveyId }),+ ['survey', 'surveyLoading', 'surveyNotifications', 'surveyNotificationsLoading'],+ ],+ actions: [+ surveyLogic({ id: props.surveyId }),+ ['loadSurveyNotifications', 'loadSurveyNotificationsSuccess', 'loadSurveySuccess'],+ ],})),actions({@@ -668,6 +678,8 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType}),closeDialog: true,setNotificationSubmissionError: (error: string | null) => ({ error }),+ setPendingDeepLink: (target: string | null) => ({ target }),+ consumePendingDeepLink: true,}),reducers({@@ -700,6 +712,13 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicTypecloseDialog: () => null,},],+ pendingDeepLink: [+ null as string | null,+ {+ setPendingDeepLink: (_, { target }) => target,+ openDialog: () => null,+ },+ ],}),forms(({ values }) => ({@@ -801,8 +820,55 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType: buildSurveyNotificationForm(values.survey))},+ setPendingDeepLink: ({ target }) => {+ if (!target) {+ return+ }+ actions.consumePendingDeepLink()+ },+ loadSurveySuccess: () => {+ if (values.pendingDeepLink) {+ actions.consumePendingDeepLink()+ }+ },+ loadSurveyNotificationsSuccess: () => {+ if (values.pendingDeepLink) {+ actions.consumePendingDeepLink()+ }+ },+ consumePendingDeepLink: () => {+ const target = values.pendingDeepLink+ if (!target || values.isOpen) {+ return+ }+ if (values.surveyLoading || values.survey.id === NEW_SURVEY.id) {+ return+ }+ if (target === 'add') {+ actions.openDialog()+ return+ }+ if (values.surveyNotificationsLoading) {+ return+ }+ const notification = values.surveyNotifications.find((fn) => fn.id === target)+ if (notification) {+ actions.openDialog({ notification, intent: 'edit' })+ return+ }+ // The notification ID didn't resolve (deleted, wrong project, stale link). Clear the+ // pending target so unrelated reloads of surveyNotifications don't keep re-triggering+ // this listener with the same dead ID, and let the user know the link didn't work.+ actions.setPendingDeepLink(null)+ lemonToast.error("We couldn't find that notification — it may have been removed.")+ },closeDialog: () => {actions.resetNotificationForm()+ // 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) {+ actions.consumePendingDeepLink()+ }},submitNotificationFormSuccess: async () => {const updatedNotification = values.editingNotification@@ -824,6 +890,25 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType)},})),++ urlToAction(({ actions, props }) => ({+ [urls.survey(props.surveyId)]: (_, searchParams) => {+ const target = searchParams.notification+ if (typeof target === 'string' && target.length > 0) {+ actions.setPendingDeepLink(target)+ }+ },+ })),++ actionToUrl(() => ({+ setPendingDeepLink: () => {+ if (!('notification' in router.values.searchParams)) {+ return+ }+ const { notification: _consumed, ...rest } = router.values.searchParams+ return [router.values.location.pathname, rest, router.values.hashParams, { replace: true }]+ },+ })),])export function getMessageFieldForDestination(destination: DestinationKey): SurveyMessageField | null {diff --git a/frontend/src/scenes/surveys/surveyNotificationsListLogic.ts b/frontend/src/scenes/surveys/surveyNotificationsListLogic.tsnew file mode 100644index 000000000000..cd18264eba56--- /dev/null+++ b/frontend/src/scenes/surveys/surveyNotificationsListLogic.ts@@ -0,0 +1,171 @@+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'++import { CyclotronJobFiltersType, HogFunctionType, Survey, SurveyEventName, SurveyEventProperties } from '~/types'++import type { surveyNotificationsListLogicType } from './surveyNotificationsListLogicType'++const SURVEY_NOTIFICATION_LIST_LIMIT = 200+const SURVEY_INDEX_LIMIT = 1000++export function getSurveyIdsFromNotificationFilters(filters?: CyclotronJobFiltersType | null): string[] {+ const surveyIds = new Set<string>()++ for (const event of filters?.events ?? []) {+ for (const property of event.properties ?? []) {+ if (property.key !== SurveyEventProperties.SURVEY_ID) {+ continue+ }++ const value = property.value+ if (Array.isArray(value)) {+ value.forEach((surveyId) => {+ if (typeof surveyId === 'string') {+ surveyIds.add(surveyId)+ }+ })+ } else if (typeof value === 'string') {+ surveyIds.add(value)+ }+ }+ }++ return Array.from(surveyIds)+}++export const surveyNotificationsListLogic = kea<surveyNotificationsListLogicType>([+ path(['scenes', 'surveys', 'surveyNotificationsListLogic']),+ actions({+ toggleNotificationEnabled: (notificationId: string, enabled: boolean) => ({ notificationId, enabled }),+ }),+ loaders(() => ({+ allNotifications: [+ [] as HogFunctionType[],+ {+ loadNotifications: async (): Promise<HogFunctionType[]> => {+ const response = await api.hogFunctions.list({+ filter_groups: [+ {+ events: [{ id: SurveyEventName.SENT, type: 'events' }],+ },+ ],+ types: ['destination'],+ limit: SURVEY_NOTIFICATION_LIST_LIMIT,+ full: true,+ })++ return response.results.filter((notification) => !notification.deleted)+ },+ },+ ],+ knownSurveys: [+ [] as Pick<Survey, 'id' | 'name' | 'archived'>[],+ {+ loadKnownSurveys: async (): Promise<Pick<Survey, 'id' | 'name' | 'archived'>[]> => {+ const response = await api.surveys.list({ limit: SURVEY_INDEX_LIMIT })+ return response.results.map((survey) => ({+ id: survey.id,+ name: survey.name,+ archived: survey.archived,+ }))+ },+ },+ ],+ })),+ reducers({+ notificationsFailed: [+ false,+ {+ loadNotifications: () => false,+ loadNotificationsSuccess: () => false,+ loadNotificationsFailure: () => true,+ },+ ],+ knownSurveysFailed: [+ false,+ {+ loadKnownSurveys: () => false,+ loadKnownSurveysSuccess: () => false,+ loadKnownSurveysFailure: () => true,+ },+ ],+ }),+ selectors({+ knownSurveyIds: [+ (s) => [s.knownSurveys],+ (knownSurveys: Pick<Survey, 'id' | 'name' | 'archived'>[]) =>+ new Set(knownSurveys.map((survey) => survey.id)),+ ],+ selectableSurveys: [+ (s) => [s.knownSurveys],+ (knownSurveys: Pick<Survey, 'id' | 'name' | 'archived'>[]) =>+ knownSurveys.filter((survey) => !survey.archived),+ ],+ notifications: [+ (s) => [s.allNotifications, s.knownSurveyIds, s.knownSurveysFailed],+ (+ allNotifications: HogFunctionType[],+ knownSurveyIds: Set<string>,+ knownSurveysFailed: boolean+ ): HogFunctionType[] => {+ // If we couldn't load the survey index, skip the existence filter and show every+ // notification we did load. The filter is just orphan cleanup — a transient+ // surveys-API failure shouldn't hide live notifications from the user.+ if (knownSurveysFailed) {+ return allNotifications+ }+ return allNotifications.filter((notification) => {+ const linkedIds = getSurveyIdsFromNotificationFilters(notification.filters)+ if (linkedIds.length === 0) {+ return false+ }+ return linkedIds.some((surveyId) => knownSurveyIds.has(surveyId))+ })+ },+ ],+ notificationsLoading: [+ (s) => [s.allNotificationsLoading, s.knownSurveysLoading],+ (allNotificationsLoading: boolean, knownSurveysLoading: boolean) =>+ allNotificationsLoading || knownSurveysLoading,+ ],+ }),+ listeners(({ actions, values }) => ({+ toggleNotificationEnabled: async ({ notificationId, enabled }) => {+ const target = values.allNotifications.find((notification) => notification.id === notificationId)+ if (!target) {+ return+ }+ const previousEnabled = target.enabled++ const applyEnabled = (next: boolean): void => {+ actions.loadNotificationsSuccess(+ values.allNotifications.map((notification) =>+ notification.id === notificationId ? { ...notification, enabled: next } : notification+ )+ )+ }++ applyEnabled(enabled)++ try {+ await api.hogFunctions.update(notificationId, { enabled })+ } catch (error) {+ applyEnabled(previousEnabled)+ lemonToast.error('Failed to update notification')+ posthog.captureException(error, {+ action: 'toggle-survey-notification-from-list',+ notification: notificationId,+ })+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadNotifications()+ actions.loadKnownSurveys()+ }),+])