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(surveys): let people add property columns to the responses table again (#107788)

Lucas Fariaddc768073203
diff --git a/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx b/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx
index 091173365e86..01afcf4aa2d5 100644
--- a/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx
+++ b/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx
@@ -5,7 +5,12 @@ import { IconLlmAnalytics, IconThumbsDown, IconThumbsUp } from '@posthog/icons'
import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
-import { SURVEY_RESPONSE_CONTEXT_COLUMNS, getSurveyResponseStatus, isScaleTwoRating } from 'scenes/surveys/utils'
+import {
+ getSurveyResponseStatus,
+ isScaleTwoRating,
+ surveyResponseColumnId,
+ surveyResponseColumnLabel,
+} from 'scenes/surveys/utils'
import { urls } from 'scenes/urls'
import { EventRowActions } from '~/queries/nodes/DataTable/EventRowActions'
@@ -39,7 +44,7 @@ export const getThumbIcon = (value: unknown): JSX.Element | null => {
* - On thumb questions, render the icon + "Thumbs up/down" instead of the raw `1`/`2` value.
*/
export function useSurveyResponseColumns(): Record<string, QueryContextColumn> {
- const { survey } = useValues(surveyLogic)
+ const { survey, responseColumns } = useValues(surveyLogic)
return useMemo(() => {
const columns: Record<string, QueryContextColumn> = {
@@ -60,9 +65,9 @@ export function useSurveyResponseColumns(): Record<string, QueryContextColumn> {
render: ({ record }) => <PersonDisplay person={(record as EventType[])[0].person} />,
},
...Object.fromEntries(
- SURVEY_RESPONSE_CONTEXT_COLUMNS.map((column): [string, QueryContextColumn] => [
- column.key,
- { title: column.label },
+ responseColumns.map((column): [string, QueryContextColumn] => [
+ surveyResponseColumnId(column),
+ { title: surveyResponseColumnLabel(column) },
])
),
actions: {
@@ -115,5 +120,5 @@ export function useSurveyResponseColumns(): Record<string, QueryContextColumn> {
})
return columns
- }, [survey.questions])
+ }, [survey.questions, responseColumns])
}
diff --git a/frontend/src/scenes/surveys/surveyLogic.test.ts b/frontend/src/scenes/surveys/surveyLogic.test.ts
index 99c0641e6489..633d9952781f 100644
--- a/frontend/src/scenes/surveys/surveyLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveyLogic.test.ts
@@ -2,6 +2,7 @@ import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import api from 'lib/api'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { dayjs } from 'lib/dayjs'
import {
mergeResponsesByQuestion,
@@ -1456,27 +1457,78 @@ describe('survey filters', () => {
expect((exportSource as { query: string }).query).not.toContain('AS response,')
})
- it('adds only the chosen context columns to the responses table and the export', async () => {
- const tableQuery = (): string => (logic.values.dataTableQuery?.source as { query: string }).query
+ it.each([
+ {
+ column: { type: TaxonomicFilterGroupType.EventProperties, key: '$current_url' } as const,
+ tableSelect: 'column_0 AS "properties.$current_url"',
+ tableRead: 'properties.$current_url AS column_0',
+ exportAlias: '"Current URL"',
+ },
+ {
+ column: { type: TaxonomicFilterGroupType.PersonProperties, key: 'plan tier' } as const,
+ tableSelect: 'column_0 AS "person.properties.plan tier"',
+ tableRead: 'person.properties."plan tier" AS column_0',
+ exportAlias: '"Person: plan tier"',
+ },
+ {
+ column: { type: TaxonomicFilterGroupType.EventProperties, key: 'Status' } as const,
+ tableSelect: 'column_0 AS "properties.Status"',
+ tableRead: 'properties.Status AS column_0',
+ exportAlias: '"Status (2)"',
+ },
+ {
+ column: {
+ type: TaxonomicFilterGroupType.EventProperties,
+ key: 'Q1: Which types of content would you like to see more of?',
+ } as const,
+ tableSelect: 'column_0 AS "properties.Q1: Which types of content would you like to see more of?"',
+ tableRead: 'properties."Q1: Which types of content would you like to see more of?" AS column_0',
+ exportAlias: '"Q1: Which types of content would you like to see more of? (2)"',
+ },
+ {
+ column: { type: TaxonomicFilterGroupType.EventProperties, key: '`a`, 1 AS `b`' } as const,
+ tableSelect: 'column_0 AS "properties.`a`, 1 AS `b`"',
+ tableRead: 'properties."`a`, 1 AS `b`" AS column_0',
+ exportAlias: '"`a`, 1 AS `b`"',
+ },
+ {
+ column: { type: 'person_id' } as const,
+ tableSelect: 'person_id AS person_id',
+ tableRead: 'argMax(person_id, tuple(timestamp, event_uuid)) AS person_id',
+ exportAlias: '"Person ID"',
+ },
+ ])(
+ 'adds the column selected as $tableSelect to the responses table and the export',
+ async ({ column, tableSelect, tableRead, exportAlias }) => {
+ const tableQuery = (): string => (logic.values.dataTableQuery?.source as { query: string }).query
+ const exportQuery = (): string => (logic.values.responsesExportQuery?.source as { query: string }).query
- await expectLogic(logic, () => {
- logic.actions.loadSurveySuccess(MULTIPLE_CHOICE_SURVEY)
- }).toDispatchActions(['loadSurveySuccess'])
+ await expectLogic(logic, () => {
+ logic.actions.loadSurveySuccess(MULTIPLE_CHOICE_SURVEY)
+ }).toDispatchActions(['loadSurveySuccess'])
- expect(tableQuery()).not.toContain('current_url')
- expect(logic.values.responsesExportQuery?.columns).not.toContain('Current URL')
+ expect(tableQuery()).not.toContain(tableSelect)
+ expect(exportQuery()).not.toContain(`AS ${exportAlias}`)
- await expectLogic(logic, () => {
- logic.actions.setResponseContextColumn('current_url', true)
- }).toDispatchActions(['setResponseContextColumn'])
-
- expect(tableQuery()).toContain('properties.`$current_url` AS current_url')
- // Row actions render in the rightmost column, so context columns come before them.
- expect(tableQuery()).toContain('current_url AS current_url,\nuuid AS actions')
- expect(tableQuery()).not.toContain('person_id AS person_id')
- expect(logic.values.responsesExportQuery?.columns).toContain('Current URL')
- expect(logic.values.responsesExportQuery?.columns).not.toContain('Person ID')
- })
+ await expectLogic(logic, () => {
+ logic.actions.addResponseColumn(column)
+ logic.actions.addResponseColumn(column)
+ }).toDispatchActions(['addResponseColumn', 'addResponseColumn'])
+
+ expect(tableQuery()).toContain(tableRead)
+ // Row actions render in the rightmost column, so chosen columns come before them.
+ expect(tableQuery()).toContain(`${tableSelect},\nuuid AS actions`)
+ expect(tableQuery().split(tableSelect)).toHaveLength(2)
+ expect(exportQuery()).toContain(`AS ${exportAlias}`)
+
+ await expectLogic(logic, () => {
+ logic.actions.removeResponseColumn(column)
+ }).toDispatchActions(['removeResponseColumn'])
+
+ expect(tableQuery()).not.toContain(tableSelect)
+ expect(exportQuery()).not.toContain(`AS ${exportAlias}`)
+ }
+ )
it('keeps question text out of the generated HogQL', async () => {
// Regression for the "Unexpected character U+00E9" crash on the Survey Results tab: a question
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index 178459eaf9b8..cb20ee51fc41 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -132,7 +132,7 @@ import {
DATE_FORMAT,
type OpenEndedColumnMap,
type SurveyQueryFilters,
- type SurveyResponseContextColumn,
+ type SurveyResponseColumn,
type SurveyResponseOutcome,
buildAggregateQuery,
buildOpenEndedQuery,
@@ -152,6 +152,7 @@ import {
isThumbQuestion,
sanitizeSurvey,
sanitizeSurveyAppearance,
+ surveyResponseColumnId,
validateSurveyAppearance,
} from './utils'
@@ -720,7 +721,7 @@ export interface surveyLogicValues {
processedSurveyStats: SurveyStats | null
projectTreeRef: ProjectTreeRef
propertyFilters: AnyPropertyFilter[]
- responseContextColumns: SurveyResponseContextColumn[]
+ responseColumns: SurveyResponseColumn[]
responsesExportQuery: DataTableNode | null
resultsFiltersExpanded: boolean
resultsRequeryInProgress: boolean
@@ -832,6 +833,9 @@ export interface surveyLogicActions {
} // eventUsageLogic
loadSurveys: () => any // surveysLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
+ addResponseColumn: (column: SurveyResponseColumn) => {
+ column: SurveyResponseColumn
+ }
archiveResponse: (responseUuid: string) => {
responseUuid: string
}
@@ -1137,6 +1141,9 @@ export interface surveyLogicActions {
removeQuestion: (questionIndex: number) => {
questionIndex: number
}
+ removeResponseColumn: (column: SurveyResponseColumn) => {
+ column: SurveyResponseColumn
+ }
resetBranchingForQuestion: (questionIndex: any) => {
questionIndex: any
}
@@ -1262,13 +1269,6 @@ export interface surveyLogicActions {
responseValue: any
specificQuestionIndex: any
}
- setResponseContextColumn: (
- column: SurveyResponseContextColumn,
- show: boolean
- ) => {
- column: 'current_url' | 'person_id' | 'session_id'
- show: boolean
- }
setResponseExpanded: (
uuid: string,
expanded: boolean
@@ -1448,7 +1448,7 @@ export interface surveyLogicMeta {
answerFilters: EventPropertyFilter[],
timestampFilter: string,
archivedResponsesFilter: string,
- responseContextColumns: ('current_url' | 'person_id' | 'session_id')[]
+ responseColumns: SurveyResponseColumn[]
) => DataTableNode | null
responsesExportQuery: (
survey: NewSurvey | Survey,
@@ -1456,7 +1456,7 @@ export interface surveyLogicMeta {
answerFilters: EventPropertyFilter[],
timestampFilter: string,
archivedResponsesFilter: string,
- responseContextColumns: ('current_url' | 'person_id' | 'session_id')[]
+ responseColumns: SurveyResponseColumn[]
) => DataTableNode | null
targetingFlagFilters: (survey: NewSurvey | Survey) => FeatureFlagFilters | undefined
urlMatchTypeValidationError: (survey: NewSurvey | Survey) => string | null
@@ -1605,7 +1605,8 @@ export const surveyLogic = kea<surveyLogicType>([
setInterval: (interval: IntervalType) => ({ interval }),
setCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),
setFilterSurveyStatsByDistinctId: (filterByDistinctId: boolean) => ({ filterByDistinctId }),
- setResponseContextColumn: (column: SurveyResponseContextColumn, show: boolean) => ({ column, show }),
+ addResponseColumn: (column: SurveyResponseColumn) => ({ column }),
+ removeResponseColumn: (column: SurveyResponseColumn) => ({ column }),
setResponseExpanded: (uuid: string, expanded: boolean) => ({ uuid, expanded }),
toggleResponseExpansion: (uuid: string) => ({ uuid }),
setBaseStatsResults: (results: SurveyBaseStatsResult) => ({ results }),
@@ -2025,6 +2026,12 @@ export const surveyLogic = kea<surveyLogicType>([
}
return {
+ addResponseColumn: ({ column }) => {
+ posthog.capture('survey response column added', { column_type: column.type })
+ },
+ removeResponseColumn: ({ column }) => {
+ posthog.capture('survey response column removed', { column_type: column.type })
+ },
createSurveySuccess: ({ survey }) => {
lemonToast.success(<>Survey {survey.name} created</>)
actions.loadSurveys()
@@ -2495,16 +2502,16 @@ export const surveyLogic = kea<surveyLogicType>([
setFilterSurveyStatsByDistinctId: (_, { filterByDistinctId }) => filterByDistinctId,
},
],
- responseContextColumns: [
- [] as SurveyResponseContextColumn[],
+ responseColumns: [
+ [] as SurveyResponseColumn[],
{ persist: true },
{
- setResponseContextColumn: (state, { column, show }) => {
- if (show === state.includes(column)) {
- return state
- }
- return show ? [...state, column] : state.filter((key) => key !== column)
- },
+ addResponseColumn: (state, { column }) =>
+ state.some((existing) => surveyResponseColumnId(existing) === surveyResponseColumnId(column))
+ ? state
+ : [...state, column],
+ removeResponseColumn: (state, { column }) =>
+ state.filter((existing) => surveyResponseColumnId(existing) !== surveyResponseColumnId(column)),
},
],
resultsRequeryInProgress: [
@@ -3097,7 +3104,7 @@ export const surveyLogic = kea<surveyLogicType>([
s.answerFilters,
s.timestampFilter,
s.archivedResponsesFilter,
- s.responseContextColumns,
+ s.responseColumns,
],
(
survey: Survey,
@@ -3105,7 +3112,7 @@ export const surveyLogic = kea<surveyLogicType>([
answerFilters: EventPropertyFilter[],
timestampFilter: string,
archivedResponsesFilter: string,
- responseContextColumns: SurveyResponseContextColumn[]
+ responseColumns: SurveyResponseColumn[]
): DataTableNode | null => {
if (survey.id === 'new') {
return null
@@ -3121,7 +3128,7 @@ export const surveyLogic = kea<surveyLogicType>([
timestampFilter,
archivedResponsesFilter,
},
- responseContextColumns
+ responseColumns
),
filters: { properties: propertyFilters },
},
@@ -3144,7 +3151,7 @@ export const surveyLogic = kea<surveyLogicType>([
s.answerFilters,
s.timestampFilter,
s.archivedResponsesFilter,
- s.responseContextColumns,
+ s.responseColumns,
],
(
survey: Survey,
@@ -3152,7 +3159,7 @@ export const surveyLogic = kea<surveyLogicType>([
answerFilters: EventPropertyFilter[],
timestampFilter: string,
archivedResponsesFilter: string,
- responseContextColumns: SurveyResponseContextColumn[]
+ responseColumns: SurveyResponseColumn[]
): DataTableNode | null => {
if (survey.id === 'new') {
return null
@@ -3164,7 +3171,7 @@ export const surveyLogic = kea<surveyLogicType>([
timestampFilter,
archivedResponsesFilter,
},
- responseContextColumns
+ responseColumns
)
return { ...query, source: { ...query.source, filters: { properties: propertyFilters } } }
},
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index 573499851289..cdb1c7c81f55 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -2,6 +2,7 @@ import DOMPurify from 'dompurify'
import { DeepPartialMap, ValidationErrorType } from 'kea-forms'
import posthog from 'posthog-js'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { dayjs } from 'lib/dayjs'
import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { getAppContext } from 'lib/utils/getAppContext'
@@ -17,7 +18,8 @@ import { urls } from 'scenes/urls'
import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import { DataTableNode, HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
-import { escapePropertyAsHogQLIdentifier } from '~/queries/utils'
+import { escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
+import { getFilterLabel } from '~/taxonomy/helpers'
import {
BasicSurveyQuestion,
CyclotronJobInvocationGlobals,
@@ -750,8 +752,8 @@ function buildMergedSubmissionsSubquery(
questions: QuestionWithIndex[],
{
includeRespondentMetadata = false,
- includeCurrentUrl = false,
- }: { includeRespondentMetadata?: boolean; includeCurrentUrl?: boolean } = {}
+ propertyReads = [],
+ }: { includeRespondentMetadata?: boolean; propertyReads?: PropertyRead[] } = {}
): string {
const completedEventExpr = `event = '${SurveyEventName.SENT}' AND ${buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_COMPLETED, 'false')}`
@@ -767,10 +769,10 @@ function buildMergedSubmissionsSubquery(
'person.properties AS person_properties',
]
: []),
- // Read only when the user turns its column on, because an unconditional read costs every
+ // Read only when the user adds its column, because an unconditional read costs every
// responses query one more property read and one more argMax. The metadata columns above
// always reach a caller, so they stay unconditional.
- ...(includeCurrentUrl ? ['properties.`$current_url` AS current_url'] : []),
+ ...propertyReads.map(({ alias, expression }) => `${expression} AS ${alias}`),
`${completedEventExpr} AS is_completed_event`,
'event',
...questions.map(({ question, index }) => `${getSurveyResponse(question, index)} AS ${rawAnswerAlias(index)}`),
@@ -793,7 +795,7 @@ function buildMergedSubmissionsSubquery(
'argMax(event, tuple(timestamp, event_uuid)) AS latest_event',
]
: []),
- ...(includeCurrentUrl ? ['argMax(current_url, tuple(timestamp, event_uuid)) AS current_url'] : []),
+ ...propertyReads.map(({ alias }) => `argMax(${alias}, tuple(timestamp, event_uuid)) AS ${alias}`),
...questions.map(({ question, index }) => {
const raw = rawAnswerAlias(index)
return `argMaxIf(${raw}, tuple(timestamp, event_uuid), ${buildAnswerPresenceExpr(raw, question)}) AS ${mergedAnswerAlias(index)}`
@@ -903,32 +905,83 @@ export function transformSurveyResponseRows(rows: DataTableRow[], survey: Pick<S
}
/**
- * Respondent context the responses table can show. Both the table and the export select only the
- * columns the user turned on, so the file carries the same context the table shows.
+ * A column the user adds to the responses table. Both the table and the export select only the
+ * columns the user added, so the file carries the same context the table shows.
*/
-export const SURVEY_RESPONSE_CONTEXT_COLUMNS = [
- { key: 'person_id', label: 'Person ID' },
- { key: 'session_id', label: 'Session ID' },
- { key: 'current_url', label: 'Current URL' },
-] as const
+export type SurveyResponseColumn =
+ | { type: 'person_id' }
+ | {
+ type: TaxonomicFilterGroupType.EventProperties | TaxonomicFilterGroupType.PersonProperties
+ key: string
+ }
-export type SurveyResponseContextColumn = (typeof SURVEY_RESPONSE_CONTEXT_COLUMNS)[number]['key']
+export function surveyResponseColumnId(column: SurveyResponseColumn): string {
+ switch (column.type) {
+ case 'person_id':
+ return 'person_id'
+ case TaxonomicFilterGroupType.EventProperties:
+ return `properties.${column.key}`
+ case TaxonomicFilterGroupType.PersonProperties:
+ return `person.properties.${column.key}`
+ }
+}
+
+export function surveyResponseColumnLabel(column: SurveyResponseColumn): string {
+ switch (column.type) {
+ case 'person_id':
+ return 'Person ID'
+ case TaxonomicFilterGroupType.EventProperties:
+ return getFilterLabel(column.key, column.type)
+ case TaxonomicFilterGroupType.PersonProperties:
+ return `Person: ${getFilterLabel(column.key, column.type)}`
+ }
+}
+
+interface PropertyRead {
+ alias: string
+ expression: string
+}
-function selectedContextColumns(
- contextColumns: SurveyResponseContextColumn[]
-): { key: SurveyResponseContextColumn; label: string }[] {
- return SURVEY_RESPONSE_CONTEXT_COLUMNS.filter((column) => contextColumns.includes(column.key))
+interface ChosenColumn {
+ column: SurveyResponseColumn
+ source: string
+}
+
+function chooseColumns(columns: SurveyResponseColumn[]): { chosen: ChosenColumn[]; propertyReads: PropertyRead[] } {
+ const chosen: ChosenColumn[] = []
+ const propertyReads: PropertyRead[] = []
+ columns.forEach((column, index) => {
+ if (column.type === 'person_id') {
+ chosen.push({ column, source: 'person_id' })
+ return
+ }
+ const alias = `column_${index}`
+ const object = column.type === TaxonomicFilterGroupType.PersonProperties ? 'person.properties' : 'properties'
+ chosen.push({ column, source: alias })
+ propertyReads.push({ alias, expression: `${object}.${escapeRawPropertyAsHogQLIdentifier(column.key)}` })
+ })
+ return { chosen, propertyReads }
+}
+
+/** A property can share its label with a fixed export column, and HogQL rejects a repeated alias. */
+function uniqueColumnName(name: string, taken: string[]): string {
+ let unique = name
+ for (let suffix = 2; taken.includes(unique); suffix++) {
+ unique = `${name} (${suffix})`
+ }
+ return unique
}
export function buildSurveyResponsesQuery(
survey: Survey,
filters: SurveyQueryFilters,
- contextColumns: SurveyResponseContextColumn[] = []
+ responseColumns: SurveyResponseColumn[] = []
): string {
const questions = getAnswerableQuestions(survey)
+ const { chosen, propertyReads } = chooseColumns(responseColumns)
const merged = buildMergedSubmissionsSubquery(survey, filters, questions, {
includeRespondentMetadata: true,
- includeCurrentUrl: contextColumns.includes('current_url'),
+ propertyReads,
})
const answers = survey.questions.map((question, index) =>
question.type !== SurveyQuestionType.Link ? mergedAnswerAlias(index) : 'NULL'
@@ -942,7 +995,9 @@ export function buildSurveyResponsesQuery(
'outcome AS status',
'submitted_at AS timestamp',
'distinct_id AS respondent',
- ...selectedContextColumns(contextColumns).map((column) => `${column.key} AS ${column.key}`),
+ ...chosen.map(
+ ({ column, source }) => `${source} AS ${escapeRawPropertyAsHogQLIdentifier(surveyResponseColumnId(column))}`
+ ),
// Last, so the row actions stay in the rightmost column.
'uuid AS actions',
]
@@ -952,12 +1007,13 @@ export function buildSurveyResponsesQuery(
export function buildSurveyResponsesExportQuery(
survey: Survey,
filters: SurveyQueryFilters,
- contextColumns: SurveyResponseContextColumn[] = []
+ responseColumns: SurveyResponseColumn[] = []
): DataTableNode & { source: HogQLQuery } {
const questions = getAnswerableQuestions(survey)
+ const { chosen, propertyReads } = chooseColumns(responseColumns)
const merged = buildMergedSubmissionsSubquery(survey, filters, questions, {
includeRespondentMetadata: true,
- includeCurrentUrl: contextColumns.includes('current_url'),
+ propertyReads,
})
const columns = ['Respondent ID', 'Email', 'Submitted at (UTC)', 'Status']
const expressions = [
@@ -967,14 +1023,14 @@ export function buildSurveyResponsesExportQuery(
"multiIf(outcome = 'completed', 'Completed', outcome = 'dismissed', 'Dismissed', 'Abandoned')",
]
- for (const column of selectedContextColumns(contextColumns)) {
- columns.push(column.label)
- expressions.push(column.key)
+ for (const { column, source } of chosen) {
+ columns.push(uniqueColumnName(surveyResponseColumnLabel(column), columns))
+ expressions.push(source)
}
for (const { question, index } of questions) {
const title = question.question.replace(/\s+/g, ' ').trim()
- columns.push(`Q${index + 1}${title ? `: ${title}` : ''}`)
+ columns.push(uniqueColumnName(`Q${index + 1}${title ? `: ${title}` : ''}`, columns))
const answer = mergedAnswerAlias(index)
expressions.push(
question.type === SurveyQuestionType.MultipleChoice
@@ -990,7 +1046,7 @@ export function buildSurveyResponsesExportQuery(
columns,
source: {
kind: NodeKind.HogQLQuery,
- query: `SELECT ${expressions.map((expression, index) => `${expression} AS ${escapePropertyAsHogQLIdentifier(columns[index])}`).join(',\n')} FROM (${merged}) ORDER BY submitted_at DESC`,
+ query: `SELECT ${expressions.map((expression, index) => `${expression} AS ${escapeRawPropertyAsHogQLIdentifier(columns[index])}`).join(',\n')} FROM (${merged}) ORDER BY submitted_at DESC`,
},
}
}
diff --git a/products/surveys/frontend/components/SurveyResponseColumnsMenu.tsx b/products/surveys/frontend/components/SurveyResponseColumnsMenu.tsx
index 8f07992f7a39..a46e675535e0 100644
--- a/products/surveys/frontend/components/SurveyResponseColumnsMenu.tsx
+++ b/products/surveys/frontend/components/SurveyResponseColumnsMenu.tsx
@@ -1,39 +1,99 @@
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+import { IconPlus, IconX } from '@posthog/icons'
import { LemonButton, LemonDropdown, LemonSwitch } from '@posthog/lemon-ui'
+import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
+import { ExcludedProperties, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { IconTuning } from 'lib/lemon-ui/icons'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
-import { SURVEY_RESPONSE_CONTEXT_COLUMNS } from 'scenes/surveys/utils'
+import { surveyResponseColumnId, surveyResponseColumnLabel } from 'scenes/surveys/utils'
+
+import { SurveyEventName } from '~/types'
+
+const PROPERTY_GROUP_TYPES = [TaxonomicFilterGroupType.EventProperties, TaxonomicFilterGroupType.PersonProperties]
export function SurveyResponseColumnsMenu(): JSX.Element {
- const { responseContextColumns } = useValues(surveyLogic)
- const { setResponseContextColumn } = useActions(surveyLogic)
+ const { responseColumns } = useValues(surveyLogic)
+ const { addResponseColumn, removeResponseColumn } = useActions(surveyLogic)
+ const [picking, setPicking] = useState(false)
+
+ const personIdShown = responseColumns.some((column) => column.type === 'person_id')
+ const addedPropertyKeys: ExcludedProperties = Object.fromEntries(
+ PROPERTY_GROUP_TYPES.map((groupType) => [
+ groupType,
+ responseColumns.flatMap((column) => (column.type === groupType ? [column.key] : [])),
+ ])
+ )
return (
<LemonDropdown
closeOnClickInside={false}
placement="bottom-end"
+ onVisibilityChange={(visible) => !visible && setPicking(false)}
overlay={
- <div className="flex flex-col gap-2 py-1 px-2 min-w-64">
- {SURVEY_RESPONSE_CONTEXT_COLUMNS.map((column) => (
+ picking ? (
+ <TaxonomicFilter
+ taxonomicGroupTypes={PROPERTY_GROUP_TYPES}
+ eventNames={[SurveyEventName.SENT]}
+ excludedProperties={addedPropertyKeys}
+ onClose={() => setPicking(false)}
+ onChange={(group, value) => {
+ if (
+ group.type === TaxonomicFilterGroupType.EventProperties ||
+ group.type === TaxonomicFilterGroupType.PersonProperties
+ ) {
+ addResponseColumn({ type: group.type, key: String(value) })
+ }
+ setPicking(false)
+ }}
+ />
+ ) : (
+ <div className="flex flex-col gap-1 py-1 px-2 min-w-64">
<LemonSwitch
- key={column.key}
- checked={responseContextColumns.includes(column.key)}
- onChange={(show) => setResponseContextColumn(column.key, show)}
- label={column.label}
+ checked={personIdShown}
+ onChange={(show) =>
+ show
+ ? addResponseColumn({ type: 'person_id' })
+ : removeResponseColumn({ type: 'person_id' })
+ }
+ label="Person ID"
fullWidth
- data-attr={`survey-response-column-${column.key}`}
+ data-attr="survey-response-column-person_id"
/>
- ))}
- </div>
+ {responseColumns.map((column) =>
+ column.type === 'person_id' ? null : (
+ <div key={surveyResponseColumnId(column)} className="flex items-center gap-2">
+ <span className="flex-1 min-w-0 truncate">{surveyResponseColumnLabel(column)}</span>
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ tooltip="Remove column"
+ onClick={() => removeResponseColumn(column)}
+ data-attr="survey-response-column-remove"
+ />
+ </div>
+ )
+ )}
+ <LemonButton
+ size="small"
+ icon={<IconPlus />}
+ onClick={() => setPicking(true)}
+ fullWidth
+ data-attr="survey-response-column-add"
+ >
+ Add column
+ </LemonButton>
+ </div>
+ )
}
>
<LemonButton
type="secondary"
size="small"
icon={<IconTuning />}
- tooltip="Choose which respondent details appear in the table and in exports"
+ tooltip="Choose which columns appear in the table and in exports"
data-attr="survey-response-columns-menu"
>
Columns