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 survey notifications tab (#58072)

Lucas Faria7d020a205e49
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx
index c8601192de97..aaebb750418c 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveySidebar.tsx
@@ -8,7 +8,6 @@ import { LemonButton, LemonMenu, LemonSelect, Link } from '@posthog/lemon-ui'
import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'
import { TZLabel } from 'lib/components/TZLabel'
import { pluralize } from 'lib/utils'
-import { SurveyNotifications } from 'scenes/surveys/components/SurveyNotifications'
import { SURVEY_TYPE_LABEL_MAP } from 'scenes/surveys/constants'
import { SurveyAppearancePreview } from 'scenes/surveys/SurveyAppearancePreview'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
@@ -187,12 +186,6 @@ export function SurveyDetailsPanel(): JSX.Element {
)
}
-export function SurveyNotificationsPanel(): JSX.Element {
- const { survey } = useValues(surveyLogic)
-
- return <SurveyNotifications surveyId={survey.id} buttonFullWidth />
-}
-
export function SurveyExportPanel(): JSX.Element {
const { survey, dataTableQuery } = useValues(surveyLogic)
const { startExport } = useActions(exportsLogic)
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
index e59688dc3f9b..680e75493991 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
@@ -19,6 +19,7 @@ import { interProjectCopyLogic } from 'scenes/resource-transfer/interProjectCopy
import { LaunchSurveyButton } from 'scenes/surveys/components/LaunchSurveyButton'
import { SurveyQuestionVisualization } from 'scenes/surveys/components/question-visualizations/SurveyQuestionVisualization'
import { SurveyFeedbackButton } from 'scenes/surveys/components/SurveyFeedbackButton'
+import { SurveyNotifications } from 'scenes/surveys/components/SurveyNotifications'
import { SurveyNotificationsCallout } from 'scenes/surveys/components/SurveyNotificationsCallout'
import { DuplicateToProjectModal } from 'scenes/surveys/DuplicateToProjectModal'
import { canDeleteSurvey, openArchiveSurveyDialog, openDeleteSurveyDialog } from 'scenes/surveys/surveyDialogs'
@@ -57,7 +58,7 @@ import { SurveyResultsRefreshStatus } from '../components/SurveyResultsRefreshSt
import { NEW_SURVEY } from '../constants'
import { SurveyDraftContent } from './SurveyDraftContent'
import { SurveyResultsFiltersBar } from './SurveyFilters'
-import { SurveyDetailsPanel, SurveyExportPanel, SurveyNotificationsPanel } from './SurveySidebar'
+import { SurveyDetailsPanel, SurveyExportPanel } from './SurveySidebar'
const RESOURCE_TYPE = 'survey'
@@ -91,11 +92,6 @@ export function SurveyViewRedesign(): JSX.Element {
label: 'Details',
content: <SurveyDetailsPanel />,
},
- {
- key: 'notifications',
- label: 'Notifications',
- content: <SurveyNotificationsPanel />,
- },
...(!isDraft
? [
{
@@ -353,6 +349,11 @@ export function SurveyViewRedesign(): JSX.Element {
},
]
: []),
+ {
+ key: SurveyTab.NOTIFICATIONS,
+ label: 'Notifications',
+ content: <SurveyNotificationsContent />,
+ },
{
key: 'history',
label: 'History',
@@ -372,6 +373,21 @@ export function SurveyViewRedesign(): JSX.Element {
)
}
+function SurveyNotificationsContent(): JSX.Element {
+ const { survey } = useValues(surveyLogic)
+
+ return (
+ <div className="px-4 pb-4">
+ <div className="mx-auto w-full max-w-[1200px]">
+ <SurveyNotifications
+ surveyId={survey.id}
+ description="Get notified whenever a survey result is submitted."
+ />
+ </div>
+ </div>
+ )
+}
+
function SurveyStatusAction(): JSX.Element | null {
const { survey } = useValues(surveyLogic)
const { stopSurvey, resumeSurvey } = useActions(surveyLogic)
diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
index 95a9500a5499..d3161ddccacd 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotificationModal.tsx
@@ -1,6 +1,7 @@
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 { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
@@ -23,6 +24,7 @@ import {
getQuestionLabel,
surveyNotificationModalLogic,
} from 'scenes/surveys/surveyNotificationModalLogic'
+import { urls } from 'scenes/urls'
import { SurveyQuestionType } from '~/types'
@@ -151,6 +153,8 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSX
templateGlobals,
submitDisabledReason,
notificationSubmissionError,
+ editingNotification,
+ copiedNotification,
} = useValues(logic)
const { closeDialog, setNotificationFormValue } = useActions(logic)
@@ -169,11 +173,32 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSX
<LemonModal
isOpen={isOpen}
onClose={closeDialog}
- title="Add survey notification"
- description="Send survey updates to Slack, Discord, Microsoft Teams, or a webhook."
+ title={
+ editingNotification
+ ? 'Edit survey notification'
+ : copiedNotification
+ ? 'Copy survey notification'
+ : 'Add survey notification'
+ }
+ description={
+ editingNotification
+ ? 'Update where this survey notification sends and what it includes.'
+ : copiedNotification
+ ? 'Review the copied notification before creating it for this survey.'
+ : 'Send survey updates to Slack, Discord, Microsoft Teams, or a webhook.'
+ }
width={720}
footer={
<>
+ {editingNotification ? (
+ <LemonButton
+ type="secondary"
+ to={urls.hogFunction(editingNotification.id)}
+ icon={<IconExternal />}
+ >
+ Open full editor
+ </LemonButton>
+ ) : null}
<LemonButton type="secondary" onClick={closeDialog}>
Cancel
</LemonButton>
@@ -184,7 +209,11 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSX
loading={isNotificationFormSubmitting}
disabledReason={submitDisabledReason}
>
- Add notification
+ {editingNotification
+ ? 'Save changes'
+ : copiedNotification
+ ? 'Create notification'
+ : 'Add notification'}
</LemonButton>
</>
}
@@ -215,6 +244,7 @@ export function SurveyNotificationModal({ surveyId }: { surveyId: string }): JSX
<img src={option.iconUrl} alt="" className="h-5 w-5 object-contain" />
),
}))}
+ disabled={!!editingNotification || !!copiedNotification}
fullWidth
/>
)}
diff --git a/frontend/src/scenes/surveys/components/SurveyNotifications.tsx b/frontend/src/scenes/surveys/components/SurveyNotifications.tsx
index 709c95fb38d8..ec5ee431615c 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotifications.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotifications.tsx
@@ -1,13 +1,12 @@
import { useActions, useValues } from 'kea'
-import { IconPlus } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
+import { IconCopy, IconPlus } from '@posthog/icons'
+import { LemonButton, LemonMenu, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'
import { NEW_SURVEY } from 'scenes/surveys/constants'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { surveyNotificationModalLogic } from 'scenes/surveys/surveyNotificationModalLogic'
-import { urls } from 'scenes/urls'
import { HogFunctionType } from '~/types'
@@ -45,11 +44,18 @@ export function SurveyNotifications({
}: SurveyNotificationsProps): JSX.Element {
const logic = surveyLogic({ id: surveyId })
const notificationModalLogic = surveyNotificationModalLogic({ surveyId })
- const { survey, surveyNotifications, surveyNotificationsLoading } = useValues(logic)
+ const {
+ survey,
+ surveyNotifications,
+ surveyNotificationsLoading,
+ reusableSurveyNotifications,
+ reusableSurveyNotificationsLoading,
+ } = useValues(logic)
const { toggleSurveyNotificationEnabled } = useActions(logic)
const { openDialog } = useActions(notificationModalLogic)
const isUnsavedSurvey = survey.id === NEW_SURVEY.id
+ const copyDisabledReason = isUnsavedSurvey ? 'Save the survey before copying notifications.' : undefined
return (
<div className="flex flex-col gap-3">
@@ -70,7 +76,7 @@ export function SurveyNotifications({
<LemonButton
type="tertiary"
size="xsmall"
- to={urls.hogFunction(fn.id)}
+ onClick={() => openDialog({ notification: fn, intent: 'edit' })}
className="font-medium p-0 h-auto min-h-0"
noPadding
>
@@ -92,17 +98,72 @@ export function SurveyNotifications({
) : (
<p className="text-xs text-muted m-0">No notifications configured yet.</p>
)}
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconPlus />}
- onClick={openDialog}
- fullWidth={buttonFullWidth}
- data-attr="survey-new-notification"
- disabledReason={isUnsavedSurvey ? 'Save the survey before adding notifications.' : undefined}
- >
- Add notification
- </LemonButton>
+ <div className={buttonFullWidth ? 'flex flex-col gap-2' : 'flex flex-wrap gap-2'}>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={() => openDialog()}
+ fullWidth={buttonFullWidth}
+ data-attr="survey-new-notification"
+ disabledReason={isUnsavedSurvey ? 'Save the survey before adding notifications.' : undefined}
+ >
+ Add notification
+ </LemonButton>
+ {reusableSurveyNotificationsLoading ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconCopy />}
+ fullWidth={buttonFullWidth}
+ loading
+ disabledReason={copyDisabledReason}
+ data-attr="survey-copy-notification"
+ >
+ Copy from existing
+ </LemonButton>
+ ) : reusableSurveyNotifications.length > 0 ? (
+ <LemonMenu
+ items={[
+ {
+ title: 'Copy from existing',
+ items: reusableSurveyNotifications.map((fn) => {
+ const notificationDescription = getNotificationDescription(fn)
+
+ return {
+ key: fn.id,
+ icon: <HogFunctionIcon src={fn.icon_url} size="small" />,
+ label: (
+ <div className="min-w-0">
+ <div className="truncate">{fn.name}</div>
+ {notificationDescription ? (
+ <div className="text-xs text-muted truncate">
+ {notificationDescription}
+ </div>
+ ) : null}
+ </div>
+ ),
+ onClick: () => openDialog({ notification: fn, intent: 'copy' }),
+ }
+ }),
+ },
+ ]}
+ placement="bottom-start"
+ maxContentWidth
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconCopy />}
+ fullWidth={buttonFullWidth}
+ disabledReason={copyDisabledReason}
+ data-attr="survey-copy-notification"
+ >
+ Copy from existing
+ </LemonButton>
+ </LemonMenu>
+ ) : null}
+ </div>
</div>
)
}
diff --git a/frontend/src/scenes/surveys/components/SurveyNotificationsCallout.tsx b/frontend/src/scenes/surveys/components/SurveyNotificationsCallout.tsx
index a806106d235b..2bfeb3ee39bd 100644
--- a/frontend/src/scenes/surveys/components/SurveyNotificationsCallout.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyNotificationsCallout.tsx
@@ -34,7 +34,7 @@ export function SurveyNotificationsCallout({ surveyId }: { surveyId: string }):
survey-specific message without leaving this page.
</div>
</div>
- <LemonButton type="primary" size="small" icon={<IconBell />} onClick={openDialog}>
+ <LemonButton type="primary" size="small" icon={<IconBell />} onClick={() => openDialog()}>
Set up notifications
</LemonButton>
</div>
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index 5d449a788e16..db30547b4b9b 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -47,6 +47,7 @@ import {
ChoiceQuestionProcessedResponses,
ChoiceQuestionResponseData,
ConsolidatedSurveyResults,
+ CyclotronJobFiltersType,
EventPropertyFilter,
FeatureFlagFilters,
HogFunctionType,
@@ -154,6 +155,32 @@ type TranslationFieldCheck<T extends string> = {
const SURVEY_QUERY_TAG_BASE = { scene: 'Survey' as const, productKey: 'surveys' as const }
const DRAFT_TRANSLATION_QUESTION_ID_PREFIX = '__draft_question_'
+const SURVEY_NOTIFICATION_LIST_LIMIT = 100
+
+function getSurveyIdsFromNotificationFilters(filters?: CyclotronJobFiltersType | null): Set<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 surveyIds
+}
function getTranslationDraftQuestionId(question: SurveyQuestion, index: number): string {
return question.id || `${DRAFT_TRANSLATION_QUESTION_ID_PREFIX}${index}`
@@ -245,6 +272,7 @@ export type SurveyDemoData = ReturnType<typeof getDemoDataForSurvey>
export enum SurveyTab {
SUMMARY = 'summary',
RESPONSES = 'responses',
+ NOTIFICATIONS = 'notifications',
HISTORY = 'history',
}
@@ -1043,6 +1071,36 @@ export const surveyLogic = kea<surveyLogicType>([
},
},
],
+ reusableSurveyNotifications: [
+ [] as HogFunctionType[],
+ {
+ loadReusableSurveyNotifications: async (): Promise<HogFunctionType[]> => {
+ if (props.id === NEW_SURVEY.id) {
+ return []
+ }
+
+ 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) => {
+ if (notification.deleted) {
+ return false
+ }
+
+ const surveyIds = getSurveyIdsFromNotificationFilters(notification.filters)
+ return !surveyIds.has(props.id)
+ })
+ },
+ },
+ ],
})),
listeners(({ actions, values, cache, props }) => {
const maybeCompleteResultsRequery = (): void => {
@@ -3102,6 +3160,7 @@ export const surveyLogic = kea<surveyLogicType>([
if (props.id !== 'new' && !shouldPreserveLocalChanges) {
actions.loadSurvey()
actions.loadSurveyNotifications()
+ actions.loadReusableSurveyNotifications()
}
if (props.id === 'new' && !shouldPreserveLocalChanges) {
actions.resetSurvey()
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
index db36cb29a839..f866dad57066 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.test.ts
@@ -1,6 +1,6 @@
import { SurveyQuestionType } from '~/types'
-import { getDefaultSurveyMessage } from './surveyNotificationModalLogic'
+import { getDefaultSurveyMessage, remapSurveyResponseProperties } from './surveyNotificationModalLogic'
describe('surveyNotificationModalLogic', () => {
it('includes survey status text in the default notification message', () => {
@@ -19,4 +19,72 @@ describe('surveyNotificationModalLogic', () => {
*Responses*
- What can we improve?: {event.properties['$survey_response_question-1']}`)
})
+
+ it('remaps copied survey response properties to the target survey questions by order', () => {
+ const copiedInputs = {
+ text: {
+ value: "First: {event.properties['$survey_response_source-a']} second: {event.properties['$survey_response_source-b']}",
+ },
+ body: {
+ value: {
+ '$survey_response_source-a': "{event.properties['$survey_response_source-a']}",
+ nested: ["{event.properties['$survey_response_source-b']}"],
+ },
+ },
+ }
+
+ expect(
+ remapSurveyResponseProperties(copiedInputs, {
+ id: 'target-survey',
+ name: 'Target survey',
+ enable_partial_responses: true,
+ questions: [
+ { id: 'target-a', question: 'First?', type: SurveyQuestionType.Open },
+ { id: 'target-b', question: 'Second?', type: SurveyQuestionType.Open },
+ ],
+ })
+ ).toEqual({
+ text: {
+ value: "First: {event.properties['$survey_response_target-a']} second: {event.properties['$survey_response_target-b']}",
+ },
+ body: {
+ value: {
+ '$survey_response_target-a': "{event.properties['$survey_response_target-a']}",
+ nested: ["{event.properties['$survey_response_target-b']}"],
+ },
+ },
+ })
+ })
+
+ it('removes copied survey response properties that do not have a target question', () => {
+ const copiedInputs = {
+ text: {
+ value: "First: {event.properties['$survey_response_source-a']} extra: {event.properties['$survey_response_source-b']}",
+ },
+ body: {
+ value: {
+ '$survey_response_source-a': "{event.properties['$survey_response_source-a']}",
+ '$survey_response_source-b': "{event.properties['$survey_response_source-b']}",
+ },
+ },
+ }
+
+ expect(
+ remapSurveyResponseProperties(copiedInputs, {
+ id: 'target-survey',
+ name: 'Target survey',
+ enable_partial_responses: true,
+ questions: [{ id: 'target-a', question: 'First?', type: SurveyQuestionType.Open }],
+ })
+ ).toEqual({
+ text: {
+ value: "First: {event.properties['$survey_response_target-a']} extra: ",
+ },
+ body: {
+ value: {
+ '$survey_response_target-a': "{event.properties['$survey_response_target-a']}",
+ },
+ },
+ })
+ })
})
diff --git a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
index dbbb8a3f1568..a48d9bc74a2e 100644
--- a/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
+++ b/frontend/src/scenes/surveys/surveyNotificationModalLogic.ts
@@ -63,6 +63,12 @@ export interface SurveyNotificationModalLogicProps {
}
type SurveyMessageField = 'slackMessage' | 'discordMessage' | 'teamsMessage'
+type HogFunctionInputValue = HogFunctionType['inputs'] extends Record<string, infer T> | null | undefined ? T : never
+export type SurveyNotificationModalIntent = 'add' | 'edit' | 'copy'
+export type OpenSurveyNotificationDialogPayload = {
+ notification?: HogFunctionType | null
+ intent?: SurveyNotificationModalIntent
+}
type SurveyNotificationContext = Pick<Survey, 'id' | 'name' | 'questions' | 'enable_partial_responses'>
type SurveyNotificationFormErrors = Partial<Record<keyof SurveyNotificationForm, string>>
@@ -229,6 +235,195 @@ function notificationNameFor(destination: DestinationKey, surveyName?: string |
return `${baseName} → ${destinationLabel}`
}
+function getSurveyResponseKeysInOrder(value: unknown): string[] {
+ const keys: string[] = []
+ const seenKeys = new Set<string>()
+
+ const collectKeys = (candidate: unknown): void => {
+ if (typeof candidate === 'string') {
+ const responseKeyRegex = /\$survey_response_[^'"\]\s,}:]+/g
+ for (const match of candidate.matchAll(responseKeyRegex)) {
+ const key = match[0]
+ if (!seenKeys.has(key)) {
+ seenKeys.add(key)
+ keys.push(key)
+ }
+ }
+ return
+ }
+
+ if (Array.isArray(candidate)) {
+ candidate.forEach(collectKeys)
+ return
+ }
+
+ if (candidate && typeof candidate === 'object') {
+ for (const [key, nestedValue] of Object.entries(candidate)) {
+ collectKeys(key)
+ collectKeys(nestedValue)
+ }
+ }
+ }
+
+ collectKeys(value)
+ return keys
+}
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+function replaceSurveyResponseKeys(
+ value: string,
+ responseKeyMap: Map<string, string>,
+ unmappedResponseKeys: Set<string>
+): string {
+ let nextValue = value
+ for (const [sourceKey, targetKey] of responseKeyMap) {
+ nextValue = nextValue.replaceAll(sourceKey, targetKey)
+ }
+ for (const sourceKey of unmappedResponseKeys) {
+ nextValue = nextValue.replace(
+ new RegExp(`\\{event\\.properties\\[['"]${escapeRegExp(sourceKey)}['"]\\]\\}`, 'g'),
+ ''
+ )
+ nextValue = nextValue.replaceAll(sourceKey, '')
+ }
+ return nextValue
+}
+
+export function remapSurveyResponseProperties<T>(value: T, survey: SurveyNotificationContext): T {
+ const targetResponseKeys = survey.questions
+ .filter((question) => question.id && question.type !== SurveyQuestionType.Link)
+ .map((question) => getSurveyIdBasedResponseKey(question.id!))
+ const sourceResponseKeys = getSurveyResponseKeysInOrder(value)
+ const responseKeyMap = new Map<string, string>()
+ const unmappedResponseKeys = new Set<string>()
+
+ sourceResponseKeys.forEach((sourceKey, index) => {
+ const targetKey = targetResponseKeys[index]
+ if (targetKey) {
+ responseKeyMap.set(sourceKey, targetKey)
+ } else {
+ unmappedResponseKeys.add(sourceKey)
+ }
+ })
+
+ const remapValue = (candidate: unknown): unknown => {
+ if (typeof candidate === 'string') {
+ return replaceSurveyResponseKeys(candidate, responseKeyMap, unmappedResponseKeys)
+ }
+
+ if (Array.isArray(candidate)) {
+ return candidate.map(remapValue)
+ }
+
+ if (candidate && typeof candidate === 'object') {
+ const remappedEntries: [string, unknown][] = []
+ for (const [key, nestedValue] of Object.entries(candidate)) {
+ const remappedKey = replaceSurveyResponseKeys(key, responseKeyMap, unmappedResponseKeys)
+ if (remappedKey) {
+ remappedEntries.push([remappedKey, remapValue(nestedValue)])
+ }
+ }
+ return Object.fromEntries(remappedEntries)
+ }
+
+ return candidate
+ }
+
+ return remapValue(value) as T
+}
+
+function getInputValue(inputs: HogFunctionType['inputs'], key: string): unknown {
+ return inputs?.[key]?.value
+}
+
+function getInputString(inputs: HogFunctionType['inputs'], key: string): string {
+ const value = getInputValue(inputs, key)
+ return typeof value === 'string' ? value : ''
+}
+
+function getInputNumber(inputs: HogFunctionType['inputs'], key: string): number | null {
+ const value = getInputValue(inputs, key)
+ return typeof value === 'number' ? value : null
+}
+
+function getDestinationForNotification(notification: HogFunctionType): DestinationKey {
+ const templateId = notification.template_id || notification.template?.id
+ return DESTINATION_OPTIONS.find((option) => option.templateId === templateId)?.value ?? 'webhook'
+}
+
+function getSlackMessageFromNotification(notification: HogFunctionType, defaultMessage: string): string {
+ const text = getInputString(notification.inputs, 'text')
+ if (text) {
+ return text
+ }
+
+ const blocks = getInputValue(notification.inputs, 'blocks')
+ if (!Array.isArray(blocks)) {
+ return defaultMessage
+ }
+
+ const section = blocks.find((block): block is { text?: { text?: unknown } } => {
+ return (
+ typeof block === 'object' &&
+ block !== null &&
+ 'type' in block &&
+ (block as { type?: unknown }).type === 'section'
+ )
+ })
+ const sectionText = section?.text?.text
+ return typeof sectionText === 'string' ? sectionText : defaultMessage
+}
+
+function getSlackIncludeButtons(notification: HogFunctionType): boolean {
+ const blocks = getInputValue(notification.inputs, 'blocks')
+ return Array.isArray(blocks)
+ ? blocks.some((block) => {
+ return (
+ typeof block === 'object' &&
+ block !== null &&
+ 'type' in block &&
+ (block as { type?: unknown }).type === 'actions'
+ )
+ })
+ : false
+}
+
+function buildSurveyNotificationFormFromNotification(
+ notification: HogFunctionType,
+ survey: SurveyNotificationContext,
+ remapResponses: boolean
+): SurveyNotificationForm {
+ const defaults = buildSurveyNotificationForm(survey)
+ const destination = getDestinationForNotification(notification)
+ const remappedInputs = remapResponses
+ ? remapSurveyResponseProperties(notification.inputs, survey)
+ : notification.inputs
+ const remappedNotification = { ...notification, inputs: remappedInputs }
+
+ return {
+ ...defaults,
+ destination,
+ slackIntegrationId: getInputNumber(remappedInputs, 'slack_workspace'),
+ slackChannel: getInputString(remappedInputs, 'channel') || null,
+ slackMessage: getSlackMessageFromNotification(remappedNotification, defaults.slackMessage),
+ includeSlackButtons: getSlackIncludeButtons(remappedNotification),
+ discordWebhookUrl: getInputString(remappedInputs, 'webhookUrl'),
+ discordMessage: getInputString(remappedInputs, 'content') || defaults.discordMessage,
+ teamsWebhookUrl: getInputString(remappedInputs, 'webhookUrl'),
+ teamsMessage: getInputString(remappedInputs, 'text') || defaults.teamsMessage,
+ webhookUrl: getInputString(remappedInputs, 'url'),
+ webhookMethod: getInputString(remappedInputs, 'method') || defaults.webhookMethod,
+ webhookBody: JSON.stringify(
+ getInputValue(remappedInputs, 'body') ?? buildWebhookBodyTemplate(survey.questions),
+ null,
+ 2
+ ),
+ }
+}
+
export function destinationDeliveryDescription(destination: DestinationKey): string {
switch (destination) {
case 'slack':
@@ -317,6 +512,96 @@ function createSurveyNotificationPayload({
}
}
+function updateSurveyNotificationPayload({
+ notification,
+ template,
+ destination,
+ surveyId,
+ form,
+}: {
+ notification: HogFunctionType
+ template: HogFunctionTemplateType
+ destination: DestinationKey
+ surveyId: string
+ form: SurveyNotificationForm
+}): Partial<HogFunctionType> {
+ const payload = createSurveyNotificationPayload({
+ template,
+ destination,
+ surveyName: null,
+ surveyId,
+ form,
+ })
+
+ return {
+ template_id: notification.template_id ?? notification.template?.id ?? payload.template_id,
+ type: notification.type,
+ name: notification.name,
+ description: notification.description,
+ inputs_schema: notification.inputs_schema ?? payload.inputs_schema,
+ enabled: notification.enabled,
+ inputs: {
+ ...notification.inputs,
+ ...(payload.inputs as Record<string, HogFunctionInputValue>),
+ },
+ mappings: notification.mappings,
+ masking: notification.masking,
+ filters: notification.filters ?? payload.filters,
+ hog: notification.hog ?? payload.hog,
+ icon_url: notification.icon_url ?? payload.icon_url,
+ }
+}
+
+function getSurveyNotificationDestinationLabel(notification: HogFunctionType): string {
+ const templateId = notification.template_id ?? notification.template?.id
+ return DESTINATION_OPTIONS.find((option) => option.templateId === templateId)?.label ?? 'Notification'
+}
+
+function createCopiedSurveyNotificationPayload({
+ notification,
+ template,
+ destination,
+ survey,
+ form,
+}: {
+ notification: HogFunctionType
+ template: HogFunctionTemplateType
+ destination: DestinationKey
+ survey: SurveyNotificationContext
+ form: SurveyNotificationForm
+}): Partial<HogFunctionType> {
+ const payload = createSurveyNotificationPayload({
+ template,
+ destination,
+ surveyName: survey.name,
+ surveyId: survey.id,
+ form,
+ })
+
+ return {
+ template_id: notification.template_id ?? notification.template?.id,
+ type: notification.type,
+ name: notificationNameFor(destination, survey.name),
+ description:
+ notification.description ||
+ `Survey notification for ${getSurveyNotificationDestinationLabel(notification)}`,
+ inputs_schema: notification.inputs_schema ?? template.inputs_schema,
+ inputs: {
+ ...(remapSurveyResponseProperties(notification.inputs ?? {}, survey) as Record<
+ string,
+ HogFunctionInputValue
+ >),
+ ...(payload.inputs as Record<string, HogFunctionInputValue>),
+ },
+ mappings: remapSurveyResponseProperties(notification.mappings, survey),
+ masking: notification.masking,
+ filters: getSurveyNotificationFilters(survey.id),
+ hog: remapSurveyResponseProperties(notification.hog, survey) ?? template.code,
+ icon_url: notification.icon_url ?? template.icon_url,
+ enabled: true,
+ }
+}
+
function getNotificationFormErrors(
form: SurveyNotificationForm,
survey: SurveyNotificationContext,
@@ -377,12 +662,29 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType
})),
actions({
- openDialog: true,
+ openDialog: (payload: OpenSurveyNotificationDialogPayload = {}) => ({
+ notification: payload.notification ?? null,
+ intent: payload.intent ?? 'add',
+ }),
closeDialog: true,
setNotificationSubmissionError: (error: string | null) => ({ error }),
}),
reducers({
+ editingNotification: [
+ null as HogFunctionType | null,
+ {
+ openDialog: (_, { notification, intent }) => (intent === 'edit' ? notification : null),
+ closeDialog: () => null,
+ },
+ ],
+ copiedNotification: [
+ null as HogFunctionType | null,
+ {
+ openDialog: (_, { notification, intent }) => (intent === 'copy' ? notification : null),
+ closeDialog: () => null,
+ },
+ ],
isOpen: [
false,
{
@@ -414,15 +716,35 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType
const templateId = DESTINATION_OPTIONS.find((option) => option.value === form.destination)?.templateId
const template = await api.hogFunctions.getTemplate(templateId || 'template-slack')
- const payload = createSurveyNotificationPayload({
- template,
- destination: form.destination,
- surveyName: values.survey.name,
- surveyId: values.survey.id,
- form,
- })
-
- await api.hogFunctions.create(payload)
+ 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,
+ })
+
+ if (values.editingNotification) {
+ await api.hogFunctions.update(values.editingNotification.id, payload)
+ } else {
+ await api.hogFunctions.create(payload)
+ }
},
},
})),
@@ -441,17 +763,29 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType
],
templateGlobals: [(s) => [s.survey], (survey: SurveyNotificationContext) => buildTemplateGlobals(survey)],
submitDisabledReason: [
- (s) => [s.survey, s.notificationFormErrors, s.isNotificationFormSubmitting],
+ (s) => [
+ s.survey,
+ s.notificationFormErrors,
+ s.isNotificationFormSubmitting,
+ s.editingNotification,
+ s.copiedNotification,
+ ],
(
survey: SurveyNotificationContext,
errors: SurveyNotificationFormErrors,
- isSubmitting: boolean
+ isSubmitting: boolean,
+ editingNotification: HogFunctionType | null,
+ copiedNotification: HogFunctionType | null
): string | undefined => {
if (survey.id === NEW_SURVEY.id) {
return 'Save the survey before creating notifications.'
}
if (isSubmitting) {
- return 'Creating notification...'
+ return editingNotification
+ ? 'Updating notification...'
+ : copiedNotification
+ ? 'Copying notification...'
+ : 'Creating notification...'
}
return (Object.values(errors).find(Boolean) as string | undefined) ?? undefined
},
@@ -459,23 +793,34 @@ export const surveyNotificationModalLogic = kea<surveyNotificationModalLogicType
}),
listeners(({ actions, values }) => ({
- openDialog: () => {
+ openDialog: ({ notification, intent }) => {
actions.resetNotificationForm()
- actions.setNotificationFormValues(buildSurveyNotificationForm(values.survey))
+ actions.setNotificationFormValues(
+ notification
+ ? buildSurveyNotificationFormFromNotification(notification, values.survey, intent === 'copy')
+ : buildSurveyNotificationForm(values.survey)
+ )
},
closeDialog: () => {
actions.resetNotificationForm()
},
submitNotificationFormSuccess: async () => {
+ const updatedNotification = values.editingNotification
+ const copiedNotification = values.copiedNotification
await actions.loadSurveyNotifications()
actions.closeDialog()
lemonToast.success(
- `Notification "${notificationNameFor(values.notificationForm.destination, values.survey.name)}" created`
+ updatedNotification
+ ? `Notification "${updatedNotification.name}" updated`
+ : copiedNotification
+ ? `Notification "${notificationNameFor(values.notificationForm.destination, values.survey.name)}" copied`
+ : `Notification "${notificationNameFor(values.notificationForm.destination, values.survey.name)}" created`
)
},
submitNotificationFormFailure: ({ error }) => {
+ const action = values.editingNotification ? 'update' : values.copiedNotification ? 'copy' : 'create'
actions.setNotificationSubmissionError(
- error instanceof Error ? error.message : 'Failed to create notification. Please try again.'
+ error instanceof Error ? error.message : `Failed to ${action} notification. Please try again.`
)
},
})),