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): always show captured partial responses (#96013)

posthog[bot]927eee7d2e82
diff --git a/docs/internal/survey-responses.md b/docs/internal/survey-responses.md
new file mode 100644
index 000000000000..b2c89cfef690
--- /dev/null
+++ b/docs/internal/survey-responses.md
@@ -0,0 +1,20 @@
+# Survey response results
+
+Survey results always include captured answers, regardless of the survey's response collection setting.
+This includes answers sent before completion and answers attached to partially completed dismissal or abandonment events.
+Changing the collection setting does not hide answers already captured.
+
+Events with the same submission ID appear as one response, with the latest available answer to each question.
+Events without a submission ID remain separate responses.
+An unfinished submission is labeled **Dismissed** when its latest response event is a dismissal, and **Abandoned** otherwise.
+**Abandoned** means no completion has been captured yet; it does not require a page-unload event or an inactivity timeout.
+A submission that later completes is shown as completed.
+
+The responses table, question charts, response counts, and summaries include these answers automatically.
+Dismissals and abandonments with no answers do not count as responses.
+
+Survey performance appears on both the Summary and Responses tabs in the redesigned survey view.
+It includes a compact row with counts and percentages for **Completed**, **Dismissed**, and **Abandoned** responses.
+These percentages use all responses matching the current filters as their denominator, including archived responses when selected.
+Each submission counts once in this breakdown, even when the performance summary counts unique people.
+The performance bar labels dismissals with no answers separately from responses.
diff --git a/ee/surveys/summaries/headline_summary.py b/ee/surveys/summaries/headline_summary.py
index 1103459ea2ba..1898d598746e 100644
--- a/ee/surveys/summaries/headline_summary.py
+++ b/ee/surveys/summaries/headline_summary.py
@@ -14,6 +14,7 @@ from posthog.hogql_queries.paginators import HogQLHasMorePaginator
from posthog.models import Team, User
from products.surveys.backend.models import Survey
+from products.surveys.backend.responses.fetch_rows import RESPONSE_EVENT_FILTER, SUBMISSION_GROUPING_KEY
from products.surveys.backend.util import get_archived_response_uuids, get_survey_response_clickhouse_query
from ee.hogai.llm import MaxChatOpenAI
@@ -104,35 +105,36 @@ def generate_survey_headline(
end_date = (survey.end_date or datetime.now()).replace(hour=23, minute=59, second=59, microsecond=0)
select_fields = []
+ merged_fields = []
for orig_idx, q in questions_with_idx:
is_multiple_choice = q.get("type", "").lower() == SurveyQuestionType.MULTIPLE_CHOICE
field = get_survey_response_clickhouse_query(orig_idx, q.get("id"), is_multiple_choice)
select_fields.append(f"{field} as q{orig_idx}")
-
- if survey.enable_partial_responses:
- partial_filter = f"AND uniqueSurveySubmissionsFilter('{survey.id}')"
- else:
- partial_filter = """AND (
- NOT JSONHas(properties, '$survey_completed')
- OR JSONExtractBool(properties, '$survey_completed') = true
- )"""
+ presence = f"length(q{orig_idx}) > 0" if is_multiple_choice else f"isNotNull(q{orig_idx})"
+ merged_fields.append(f"argMaxIf(q{orig_idx}, timestamp, {presence}) as answer_{orig_idx}")
# Get archived response UUIDs to exclude
# UUIDs are pre-validated by Django's UUIDField when stored in SurveyResponseArchive
archived_uuids = get_archived_response_uuids(survey.id, team.pk)
- archived_filter = " AND uuid NOT IN {exclude_uuids}" if archived_uuids else ""
+ archived_filter = " HAVING response_uuid NOT IN {exclude_uuids}" if archived_uuids else ""
with timer("query"):
query = f"""
- SELECT {", ".join(select_fields)}
- FROM events
- WHERE event == 'survey sent'
- AND properties.$survey_id = {{survey_id}}
- AND timestamp >= {{start_date}}
- AND timestamp <= {{end_date}}
- {partial_filter}
+ SELECT {", ".join(f"answer_{idx}" for idx, _ in questions_with_idx)}
+ FROM (
+ SELECT {", ".join(merged_fields)}, argMax(uuid, timestamp) as response_uuid,
+ max(timestamp) as submitted_at
+ FROM (
+ SELECT {", ".join(select_fields)}, uuid, timestamp,
+ {SUBMISSION_GROUPING_KEY} as submission_key
+ FROM events
+ WHERE {RESPONSE_EVENT_FILTER}
+ AND properties.$survey_id = {{survey_id}}
+ AND timestamp >= {{start_date}}
+ AND timestamp <= {{end_date}}
+ ) GROUP BY submission_key
{archived_filter}
- ORDER BY timestamp DESC
+ ) ORDER BY submitted_at DESC
"""
placeholders: dict[str, ast.Expr] = {
diff --git a/ee/surveys/summaries/summarize_surveys.py b/ee/surveys/summaries/summarize_surveys.py
index 597b5a54d933..0422102d3aaa 100644
--- a/ee/surveys/summaries/summarize_surveys.py
+++ b/ee/surveys/summaries/summarize_surveys.py
@@ -7,13 +7,15 @@ from posthoganalytics.ai.openai import OpenAI
from prometheus_client import Histogram
from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.api.utils import ServerTimingsGathered
from posthog.hogql_queries.paginators import HogQLHasMorePaginator
from posthog.models import Team, User
from posthog.utils import get_instance_region
+from products.surveys.backend.responses.fetch_rows import RESPONSE_EVENT_FILTER, SUBMISSION_GROUPING_KEY
+
logger = structlog.get_logger(__name__)
TOKENS_IN_PROMPT_HISTOGRAM = Histogram(
@@ -61,16 +63,22 @@ def summarize_survey_responses(
paginator = HogQLHasMorePaginator(limit=100, offset=0)
q = parse_select(
"""
- SELECT getSurveyResponse({question_index}, {question_id})
- FROM events
- WHERE event == 'survey sent'
- AND properties.$survey_id = {survey_id}
- AND trim(getSurveyResponse({question_index}, {question_id})) != ''
- AND timestamp >= {start_date}
- AND timestamp <= {end_date}
+ SELECT argMaxIf(answer, timestamp, isNotNull(answer)) AS response
+ FROM (
+ SELECT getSurveyResponse({question_index}, {question_id}) AS answer,
+ timestamp, {submission_key} AS submission_key
+ FROM events
+ WHERE {response_events}
+ AND properties.$survey_id = {survey_id}
+ AND timestamp >= {start_date}
+ AND timestamp <= {end_date}
+ ) GROUP BY submission_key
+ HAVING length(trim(coalesce(response, ''))) > 0
""",
{
"survey_id": ast.Constant(value=survey_id),
+ "response_events": parse_expr(RESPONSE_EVENT_FILTER),
+ "submission_key": parse_expr(SUBMISSION_GROUPING_KEY),
"survey_response_property": ast.Constant(
value=f"$survey_response_{question_index}" if question_index else "$survey_response"
),
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2293685be052..22107cffc09a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9077,9 +9077,9 @@ snapshots:
scenes-app-surveys--new-survey-with-text-question-description-that-does-not-render-html--light:
hash: v1.k794b7964.bdd6755a72ec571efaa9b38ef0bff6e87b78d504b254006a409f2114354d7afc.tu-CzwdxzR8jjFs-Eam3yR-MQDTaJGOSQFTevQSXczE
scenes-app-surveys--survey-results--dark:
- hash: v1.k794b7964.593d9cfd1f47b2ff7296eb4d5e2e31be1636bd2a39a9b350b4c1b5e157684cbb.al8-igeJ8c_xg1N5V4_LD874kwxo1rnKFtrfQGu3daY
+ hash: v1.k794b7964.22429f3caf472f93e8f3a559cc2738beaa7112af411cc1c542480685f61e5dec.CQ4JZFOylj8lzITVjGi1Y2SeDwVj5Mig5H_66rgrmQg
scenes-app-surveys--survey-results--light:
- hash: v1.k794b7964.159d3336c210da231f8f6481bead2cc41f0df60afe12c6246e15908c08c5c8d5.117vRRDfT1RdtLO665SJ_jl7mgyw_lsV_nGHhOtXuEk
+ hash: v1.k794b7964.1e0e0ee6efe5940b1a201836f1e8760d2e2d35ce4410cadc852a513c55fa0d4f.-m_nJ8aoNAoq4vnD9GtN2eA2GF8oGdqh24wqUdZI-lI
scenes-app-surveys--surveys-global-settings--dark:
hash: v1.k794b7964.476a85556bb374416ca1ae0cccfb23f8cc6f6a2e0e71d3f7d0e37a2ad3d463aa.lCKgctegJe2jQZ7Bf7sXK6YhuGh17KhGftYqoY3s5PM
scenes-app-surveys--surveys-global-settings--light:
@@ -9984,6 +9984,22 @@ snapshots:
hash: v1.k794b7964.4c1cd99854b96691ddb9e08ec324cccac42c1f98ee451adc2cafc240845100df.AolTmj-cZB22E17CR-MrJLtErCR7ZFqQIKpdK_hCngs
scenes-web-analytics-calendarheatmap--with-hidden-row-aggregation--light:
hash: v1.k794b7964.afd498e7ebdeb0ae332637bc81c11e42462d4e849279096bc98b32e0cd80a516.a801UVBIEm5FXhf9KT5H6yJS0fMpnWS9Fv3lBzmSbqs
+ surveys-surveyresponsebreakdown--dismissal-only--dark:
+ hash: v1.k794b7964.dc398f0718022d46e2f37f1a5887a9f68de06d1a171a85f2e9cb573e7e177e93.fQmkJPE1SgLkSfm4JFSTgQBK3CMCjPsI0oP9cg-mV0Q
+ surveys-surveyresponsebreakdown--dismissal-only--light:
+ hash: v1.k794b7964.7eb1c30d6b939e96283c0a1f5f57bea2ed25802df999bf2db229dfb4b69c46d6.aRZN4z1D8O2NV9ZUKIzLoCp2dDmC3-2oq1XN5NyNCMk
+ surveys-surveyresponsebreakdown--empty--dark:
+ hash: v1.k794b7964.9bf18bdba89b891cbab00721d05a7a100c5ae0db8a6d8eba3d8d0223ba1b10fe.EjgNzCzs0UH8tBsX-IUoG69COapNDUm79qOfbVbi4tU
+ surveys-surveyresponsebreakdown--empty--light:
+ hash: v1.k794b7964.0fd417b0019402591594144c062e93130ba2c5e290ef531bc5270df2602d6803.Bm_cTBOKKWMZ9ABq-g-4TUdsBikRrXEvPWgxJqqdXlU
+ surveys-surveyresponsebreakdown--mixed--dark:
+ hash: v1.k794b7964.57dcdd3cc4fc49910ddd81c9119d6f2771bd3b2a5c16bdd818719c94a43435cb.M-q5xfK5xZFN5WyOsZPIP3XKJrMV3bxdjn4PUkqK21o
+ surveys-surveyresponsebreakdown--mixed--light:
+ hash: v1.k794b7964.d539d4694b8c0bf0400042382753fee4862837a552814a3ea73398fa1be9681c.jLHwTqtKqBkf5Ca-_NkoFb5HYph57R2X2HpK7aljPvY
+ surveys-surveyresponsebreakdown--narrow--dark:
+ hash: v1.k794b7964.c0cf6c831ccad908f97f99e47f81a6e3b95c56897f7f72e81ca841d512b70186.9safzbuqrXolVYOfDuVnKiUZlvlKXV2ra0evCXgAfjc
+ surveys-surveyresponsebreakdown--narrow--light:
+ hash: v1.k794b7964.f3acbfd20c86d9238a86d3c4895eb723bfbf579147df285a398702b247307041.iUWLCgfZaqLie9OoCaHO-Q0TK0W25NjG_UF1mE57VSA
ui-buttonprimitive--default--dark:
hash: v1.k794b7964.491cb9dec34de5e64508adc9f3885a05ae8badea99d214a14ae96bb2cf4911a9.JVM8RfbvLA_ZeObFGGMZk_GmhYoddhG-HxFT7yY2Ts8
ui-buttonprimitive--default--light:
diff --git a/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx b/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx
index 4499c1395a28..ca8ec1b93757 100644
--- a/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx
+++ b/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx
@@ -8,9 +8,10 @@ import { HTMLElementsDisplay } from 'lib/components/HTMLElementsDisplay/HTMLElem
import { dayjs } from 'lib/dayjs'
import { LemonTab, LemonTabs, LemonTabsProps } from 'lib/lemon-ui/LemonTabs'
import { isKeyOf } from 'lib/utils/guards'
+import { isSurveyResponseEvent } from 'scenes/surveys/utils'
import { CORE_FILTER_DEFINITIONS_BY_GROUP, POSTHOG_EVENT_PROMOTED_PROPERTIES } from '~/taxonomy/taxonomy'
-import { EventType, RecordingEventType, SurveyEventProperties } from '~/types'
+import { EventType, RecordingEventType } from '~/types'
import { AutocaptureImageTab, hasAutocaptureImage } from '../AutocapturePreviewImage/AutocapturePreviewImage'
import { ErrorEventType } from '../Errors/types'
@@ -59,7 +60,7 @@ export const EventPropertyTabs = ({
const isAITagEvent = event.event === '$ai_tag'
const isErrorEvent = event.event === '$exception'
- const isSurveyResponseEvent = event.event === 'survey sent' && !!event.properties?.[SurveyEventProperties.SURVEY_ID]
+ const hasSurveyResponse = isSurveyResponseEvent(event.event, event.properties || {})
const isMcpEvent =
typeof event.event === 'string' &&
(event.event.startsWith('mcp_') || event.event.startsWith('$mcp_') || event.event.startsWith('mcp '))
@@ -75,7 +76,7 @@ export const EventPropertyTabs = ({
? 'tag'
: isErrorEvent
? 'error_display'
- : isSurveyResponseEvent
+ : hasSurveyResponse
? 'survey_response'
: isMcpEvent
? 'mcp'
@@ -121,7 +122,7 @@ export const EventPropertyTabs = ({
label: 'Exception',
content: tabContentComponentFn({ event, properties: event.properties, tabKey: 'error_display' }),
},
- isSurveyResponseEvent && {
+ hasSurveyResponse && {
key: 'survey_response',
label: 'Survey response',
content: tabContentComponentFn({ event, properties: event.properties, tabKey: 'survey_response' }),
diff --git a/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx b/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx
index 2abb328dff44..45b1221586fc 100644
--- a/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx
+++ b/frontend/src/lib/components/SurveyResponseDisplay/SurveyResponseDisplay.tsx
@@ -12,13 +12,14 @@ import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { NewSurvey } from 'scenes/surveys/constants'
import { getThumbIcon } from 'scenes/surveys/hooks/useSurveyResponseColumns'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
-import { getSurveyResponseValue, isScaleTwoRating } from 'scenes/surveys/utils'
+import { getSurveyResponseStatus, getSurveyResponseValue, isScaleTwoRating } from 'scenes/surveys/utils'
import { urls } from 'scenes/urls'
import { Survey, SurveyEventProperties as SurveyEventPropertyNames, SurveyQuestion } from '~/types'
interface SurveyResponseDisplayProps {
eventProperties: Record<string, any>
+ eventName?: string
eventUuid?: string
distinctId?: string
timestamp?: string | null
@@ -87,6 +88,7 @@ function SurveyResponseDisplayWithLogic({
function SurveyResponseContent({
eventProperties,
+ eventName,
eventUuid,
distinctId,
timestamp,
@@ -106,9 +108,7 @@ function SurveyResponseContent({
const surveyName = survey?.name || eventProperties['$survey_name']
const iteration = eventProperties[SurveyEventPropertyNames.SURVEY_ITERATION]
- const isPartial =
- eventProperties[SurveyEventPropertyNames.SURVEY_COMPLETED] === false ||
- eventProperties[SurveyEventPropertyNames.SURVEY_PARTIALLY_COMPLETED] === true
+ const partialStatus = getSurveyResponseStatus(eventName, eventProperties)
const sessionId = typeof eventProperties.$session_id === 'string' ? eventProperties.$session_id : undefined
const currentUrl = typeof eventProperties.$current_url === 'string' ? eventProperties.$current_url : null
@@ -126,7 +126,7 @@ function SurveyResponseContent({
const libraryLine = [lib, libVersion].filter(Boolean).join(' ')
const hasFooter = currentUrl || deviceLine || locationLine || libraryLine
- const hasHeaderMeta = distinctId || timestamp || sessionId || isPartial || isArchived || iteration != null
+ const hasHeaderMeta = distinctId || timestamp || sessionId || partialStatus || isArchived || iteration != null
const responses: { questionIndex: number; question: SurveyQuestion; value: any }[] = []
@@ -170,9 +170,9 @@ function SurveyResponseContent({
checkRecordingExists
/>
)}
- {isPartial && (
+ {partialStatus && (
<LemonTag type="warning" size="small">
- Partial
+ {partialStatus}
</LemonTag>
)}
{isArchived && (
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsx
index fea2ad9060b2..dedf912fddd2 100644
--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx
@@ -976,6 +976,7 @@ export function DataTable({
query={query}
setQuery={setQuery}
fileNameForExport={context?.fileNameForExport}
+ excludedColumns={context?.dataTableExportExcludedColumns}
/>
) : null,
showExport && showOpenEditorButton ? (
diff --git a/frontend/src/queries/nodes/DataTable/DataTableExport.tsx b/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
index 4f6ea459b3ef..d3aa482dc71e 100644
--- a/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
@@ -12,7 +12,12 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
-import { copyTableToCsv, copyTableToExcel, copyTableToJson } from '~/queries/nodes/DataTable/clipboardUtils'
+import {
+ copyTableToCsv,
+ copyTableToExcel,
+ copyTableToJson,
+ projectExportRows,
+} from '~/queries/nodes/DataTable/clipboardUtils'
import {
shouldOptimizeForExport,
transformColumnsForExport,
@@ -113,11 +118,22 @@ interface DataTableExportProps {
query: DataTableNode
setQuery?: (query: DataTableNode) => void
fileNameForExport?: string
+ excludedColumns?: string[]
}
-export function DataTableExport({ query, fileNameForExport }: DataTableExportProps): JSX.Element | null {
+export function DataTableExport({
+ query,
+ fileNameForExport,
+ excludedColumns = [],
+}: DataTableExportProps): JSX.Element | null {
const { dataTableRows, columnsInResponse, columnsInQuery, queryWithDefaults } = useValues(dataTableLogic)
const { startExport, createStaticCohort } = useActions(exportsLogic)
+ const responseColumns = columnsInResponse ?? columnsInQuery
+ const exportColumns = responseColumns.filter((column) => !excludedColumns.includes(column))
+ const exportQuery = excludedColumns.length ? { ...query, columns: exportColumns } : query
+ const exportRows = excludedColumns.length
+ ? projectExportRows(dataTableRows ?? [], responseColumns, exportColumns)
+ : dataTableRows
const source: DataNode = query.source
const filterCount =
@@ -148,13 +164,25 @@ export function DataTableExport({ query, fileNameForExport }: DataTableExportPro
{
label: 'CSV',
onClick: () => {
- void startDownload(query, true, startExport, ExporterFormat.CSV, fileNameForExport)
+ void startDownload(
+ exportQuery,
+ true,
+ startExport,
+ ExporterFormat.CSV,
+ fileNameForExport
+ )
},
},
{
label: 'XLSX',
onClick: () => {
- void startDownload(query, true, startExport, ExporterFormat.XLSX, fileNameForExport)
+ void startDownload(
+ exportQuery,
+ true,
+ startExport,
+ ExporterFormat.XLSX,
+ fileNameForExport
+ )
},
},
],
@@ -165,12 +193,24 @@ export function DataTableExport({ query, fileNameForExport }: DataTableExportPro
{
label: 'CSV',
onClick: () =>
- void startDownload(query, false, startExport, ExporterFormat.CSV, fileNameForExport),
+ void startDownload(
+ exportQuery,
+ false,
+ startExport,
+ ExporterFormat.CSV,
+ fileNameForExport
+ ),
},
{
label: 'XLSX',
onClick: () =>
- void startDownload(query, false, startExport, ExporterFormat.XLSX, fileNameForExport),
+ void startDownload(
+ exportQuery,
+ false,
+ startExport,
+ ExporterFormat.XLSX,
+ fileNameForExport
+ ),
},
],
},
@@ -180,12 +220,8 @@ export function DataTableExport({ query, fileNameForExport }: DataTableExportPro
{
label: 'CSV',
onClick: () => {
- if (dataTableRows) {
- copyTableToCsv(
- dataTableRows,
- columnsInResponse ?? columnsInQuery,
- queryWithDefaults
- )
+ if (exportRows) {
+ copyTableToCsv(exportRows, exportColumns, queryWithDefaults)
}
},
'data-attr': 'copy-csv-to-clipboard',
@@ -193,12 +229,8 @@ export function DataTableExport({ query, fileNameForExport }: DataTableExportPro
{
label: 'JSON',
onClick: () => {
- if (dataTableRows) {
- copyTableToJson(
- dataTableRows,
- columnsInResponse ?? columnsInQuery,
- queryWithDefaults
- )
+ if (exportRows) {
+ copyTableToJson(exportRows, exportColumns, queryWithDefaults)
}
},
'data-attr': 'copy-json-to-clipboard',
@@ -206,12 +238,8 @@ export function DataTableExport({ query, fileNameForExport }: DataTableExportPro
{
label: 'Excel',
onClick: () => {
- if (dataTableRows) {
- copyTableToExcel(
- dataTableRows,
- columnsInResponse ?? columnsInQuery,
- queryWithDefaults
- )
+ if (exportRows) {
+ copyTableToExcel(exportRows, exportColumns, queryWithDefaults)
}
},
'data-attr': 'copy-excel-to-clipboard',
diff --git a/frontend/src/queries/nodes/DataTable/EventRowActions.tsx b/frontend/src/queries/nodes/DataTable/EventRowActions.tsx
index be5e84d78b2e..eed36ad2f9c3 100644
--- a/frontend/src/queries/nodes/DataTable/EventRowActions.tsx
+++ b/frontend/src/queries/nodes/DataTable/EventRowActions.tsx
@@ -10,11 +10,12 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { insightUrlForEvent } from 'scenes/insights/utils'
import { ArchiveSurveyButton } from 'scenes/surveys/components/ArchiveSurveyButton'
+import { isSurveyResponseEvent } from 'scenes/surveys/utils'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { saveActionFromEvent } from '~/models/saveAsActionDialog'
-import { EventType, SurveyEventName } from '~/types'
+import { EventType } from '~/types'
export function EventRowActions({
event,
@@ -59,7 +60,7 @@ function EventRowActionsDropdown({ event }: { event: EventType }): JSX.Element {
Create action from event
</LemonButton>
)}
- {event.event === SurveyEventName.SENT && event.uuid && event.properties.$survey_id ? (
+ {isSurveyResponseEvent(event.event, event.properties) && event.uuid && event.properties.$survey_id ? (
<ArchiveSurveyButton surveyId={event.properties.$survey_id} responseUuid={event.uuid} />
) : null}
{event.uuid && event.timestamp && <EventCopyLinkButton event={event} />}
diff --git a/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts b/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
index 81ba372e5a57..90f78e15267f 100644
--- a/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
+++ b/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
@@ -14,6 +14,7 @@ import {
flattenObject,
getCsvTableData,
getJsonTableData,
+ projectExportRows,
} from './clipboardUtils'
import { DataTableRow } from './dataTableLogic'
@@ -451,3 +452,12 @@ describe('clipboardUtils', () => {
})
})
})
+
+describe('projectExportRows', () => {
+ it('preserves answer and outcome columns while excluding internal row metadata', () => {
+ const rows = [{ result: [{ properties: { internal: true } }, 'Useful examples', 'dismissed', 'event-id'] }]
+ expect(projectExportRows(rows, ['response', 'answer', 'status', 'actions'], ['answer', 'status'])).toEqual([
+ { result: ['Useful examples', 'dismissed'] },
+ ])
+ })
+})
diff --git a/frontend/src/queries/nodes/DataTable/clipboardUtils.ts b/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
index db2cf0111719..083281378004 100644
--- a/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
+++ b/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
@@ -17,6 +17,14 @@ import {
import { DataTableRow } from './dataTableLogic'
+export function projectExportRows(rows: DataTableRow[], columns: string[], exportColumns: string[]): DataTableRow[] {
+ const indexes = exportColumns.map((column) => columns.indexOf(column))
+ return rows.map((row) => {
+ const result = row.result
+ return Array.isArray(result) ? { ...row, result: indexes.map((index) => result[index]) } : row
+ })
+}
+
const columnDisallowList = ['person.$delete', '*']
// Helper function to recursively flatten objects for CSV export
diff --git a/frontend/src/queries/types.ts b/frontend/src/queries/types.ts
index f9ae361b1d25..c9653b8e42bd 100644
--- a/frontend/src/queries/types.ts
+++ b/frontend/src/queries/types.ts
@@ -51,6 +51,7 @@ export interface QueryContext<Q extends QuerySchema = QuerySchema> {
showLoadNextButton?: boolean
/** Allow customization of file name when exporting */
fileNameForExport?: string
+ dataTableExportExcludedColumns?: string[]
/** Cohort ID to enable cohort-specific features like View Replays button */
cohortId?: number | null
/** Custom column features to pass down to the DataTable */
diff --git a/frontend/src/scenes/activity/explore/EventDetails.tsx b/frontend/src/scenes/activity/explore/EventDetails.tsx
index b99e1327dfa3..804931a6be5f 100644
--- a/frontend/src/scenes/activity/explore/EventDetails.tsx
+++ b/frontend/src/scenes/activity/explore/EventDetails.tsx
@@ -115,6 +115,7 @@ export function EventDetails({ event, tableProps }: EventDetailsProps): JSX.Elem
return (
<div className="mx-3">
<SurveyResponseDisplay
+ eventName={event.event}
eventProperties={properties}
eventUuid={'uuid' in event && event.uuid ? event.uuid : undefined}
distinctId={'distinct_id' in event ? event.distinct_id : undefined}
diff --git a/frontend/src/scenes/surveys/SurveySQLHelper.tsx b/frontend/src/scenes/surveys/SurveySQLHelper.tsx
index 476b72f8dd81..7a33a1f1fc3e 100644
--- a/frontend/src/scenes/surveys/SurveySQLHelper.tsx
+++ b/frontend/src/scenes/surveys/SurveySQLHelper.tsx
@@ -1,6 +1,5 @@
import { useValues } from 'kea'
import { router } from 'kea-router'
-import { SurveyQuestionType } from 'posthog-js'
import { LemonButton, LemonDivider, LemonModal } from '@posthog/lemon-ui'
@@ -9,14 +8,9 @@ import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
import { urls } from 'scenes/urls'
-import { Survey, SurveyEventName, SurveyEventProperties, SurveyQuestion } from '~/types'
+import { Survey, SurveyQuestion } from '~/types'
-import { buildPartialResponsesFilter, createAnswerFilterHogQLExpression } from './utils'
-
-function escapeSqlIdentifier(value: string): string {
- // Collapse newlines first (a multi-line alias is undesirable and fragile), then escape quotes.
- return value.replace(/\s*[\r\n]+\s*/g, ' ').replace(/"/g, '""')
-}
+import { buildSurveyResponseSQLQuery } from './utils'
interface SurveySQLHelperProps {
isOpen: boolean
@@ -24,55 +18,9 @@ interface SurveySQLHelperProps {
}
export function SurveySQLHelper({ isOpen, onClose }: SurveySQLHelperProps): JSX.Element {
- const { survey, answerFilters } = useValues(surveyLogic)
-
- const filterConditions = createAnswerFilterHogQLExpression(answerFilters, survey as Survey)
-
- const generateSingleQuestionQuery = (question: SurveyQuestion, index: number): string => {
- return `SELECT
- distinct_id,
- getSurveyResponse(${index}, '${question.id}'${
- question.type === SurveyQuestionType.MultipleChoice ? ', true' : ''
- }) AS "${escapeSqlIdentifier(question.question)}",
- timestamp
-FROM
- events
-WHERE
- event = '${SurveyEventName.SENT}'
- AND properties.${SurveyEventProperties.SURVEY_ID} = '${survey.id}'
- ${buildPartialResponsesFilter(survey as Survey)}
- ${filterConditions ? filterConditions : ''}
-ORDER BY
- timestamp DESC
-LIMIT
- 100`
- }
-
- const generateFullSurveyQuery = (): string => {
- const questionSelects = survey.questions
- .map((question: SurveyQuestion, index: number) => {
- return ` getSurveyResponse(${index}, '${question.id}'${
- question.type === SurveyQuestionType.MultipleChoice ? ', true' : ''
- }) AS "${escapeSqlIdentifier(question.question)}"`
- })
- .join(',\n')
-
- return `SELECT
- distinct_id,
-${questionSelects},
- timestamp
-FROM
- events
-WHERE
- event = '${SurveyEventName.SENT}'
- AND properties.${SurveyEventProperties.SURVEY_ID} = '${survey.id}'
- ${buildPartialResponsesFilter(survey as Survey)}
- ${filterConditions ? filterConditions : ''}
-ORDER BY
- timestamp DESC
-LIMIT
- 100`
- }
+ const { survey, answerFilters, timestampFilter, archivedResponsesFilter } = useValues(surveyLogic)
+ const queryFilters = { answerFilters, timestampFilter, archivedResponsesFilter }
+ const fullSurveyQuery = buildSurveyResponseSQLQuery(survey as Survey, queryFilters)
// Function to open query in a new insight
const openInInsight = (query: string): void => {
@@ -89,7 +37,7 @@ LIMIT
<p>
<b>Important:</b> Since March 7, 2025, survey responses are stored using question IDs
([UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)) instead of indexes. The
- queries below handle both formats using the <code>coalesce</code> function.
+ queries below merge captured answers from both formats into one row per submission.
</p>
<p>
<b>Note:</b> These queries only include response filters set on the table. Additional property
@@ -110,13 +58,13 @@ LIMIT
<LemonButton
icon={<IconOpenInNew />}
size="small"
- onClick={() => openInInsight(generateFullSurveyQuery())}
+ onClick={() => openInInsight(fullSurveyQuery)}
tooltip="Open as new insight"
noPadding
/>
}
>
- {generateFullSurveyQuery()}
+ {fullSurveyQuery}
</CodeSnippet>
</div>
@@ -137,13 +85,17 @@ LIMIT
<LemonButton
icon={<IconOpenInNew />}
size="small"
- onClick={() => openInInsight(generateSingleQuestionQuery(question, index))}
+ onClick={() =>
+ openInInsight(
+ buildSurveyResponseSQLQuery(survey as Survey, queryFilters, index)
+ )
+ }
tooltip="Open as new insight"
noPadding
/>
}
>
- {generateSingleQuestionQuery(question, index)}
+ {buildSurveyResponseSQLQuery(survey as Survey, queryFilters, index)}
</CodeSnippet>
</div>
))}
diff --git a/frontend/src/scenes/surveys/SurveyStatsSummary.tsx b/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
index 35d002b58147..40c9ac1885d6 100644
--- a/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
+++ b/frontend/src/scenes/surveys/SurveyStatsSummary.tsx
@@ -13,6 +13,8 @@ import { CopySurveyLink } from 'scenes/surveys/CopySurveyLink'
import { SurveyEventName, SurveyRates, SurveyStats, SurveyType } from '~/types'
+import { SurveyResponseBreakdown } from 'products/surveys/frontend/components/SurveyResponseBreakdown'
+
import { surveyLogic } from './surveyLogic'
interface StatRowItem {
@@ -159,13 +161,13 @@ function SurveyStatsStackedBar({
const segments: StackedBarSegment[] = [
{
count: sent,
- label: 'Submitted',
+ label: 'Responses',
colorClass: 'bg-success',
tooltip: getTooltip(sent, total, filterByDistinctId),
},
{
count: dismissed,
- label: 'Dismissed',
+ label: 'Dismissed without answers',
colorClass: 'bg-warning',
tooltip: getTooltip(dismissed, total, filterByDistinctId),
},
@@ -308,6 +310,7 @@ export const SurveyStatsSummary = memo(function SurveyStatsSummary(): JSX.Elemen
surveyBaseStatsLoading,
surveyDismissedAndSentCountLoading,
resultsRequeryInProgress,
+ surveyResponseOutcomes,
} = useValues(surveyLogic)
if (
@@ -337,6 +340,7 @@ export const SurveyStatsSummary = memo(function SurveyStatsSummary(): JSX.Elemen
</>
)}
<SurveyStatsStackedBar stats={processedSurveyStats} filterByDistinctId={filterSurveyStatsByDistinctId} />
+ {surveyResponseOutcomes && <SurveyResponseBreakdown outcomes={surveyResponseOutcomes} />}
</SurveyStatsContainer>
)
})
diff --git a/frontend/src/scenes/surveys/SurveyView.tsx b/frontend/src/scenes/surveys/SurveyView.tsx
index f7e4a544dae4..905976e3a0e4 100644
--- a/frontend/src/scenes/surveys/SurveyView.tsx
+++ b/frontend/src/scenes/surveys/SurveyView.tsx
@@ -39,6 +39,8 @@ import { SurveyResultDemo } from 'scenes/surveys/SurveyResultDemo'
import { surveysLogic } from 'scenes/surveys/surveysLogic'
import { SurveyStatsSummary } from 'scenes/surveys/SurveyStatsSummary'
import { SurveyViewRedesign } from 'scenes/surveys/SurveyViewRedesign'
+import { SurveyResponseExpandedRow } from 'scenes/surveys/SurveyViewRedesign/SurveyResponseExpandedRow'
+import { transformSurveyResponseRows } from 'scenes/surveys/utils'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -416,6 +418,16 @@ export function SurveyResult({ disableEventsTable }: { disableEventsTable?: bool
query={dataTableQuery}
context={{
columns: surveyColumnRenderers,
+ expandable: {
+ expandedRowRender: ({ result }) => (
+ <SurveyResponseExpandedRow result={result} />
+ ),
+ rowExpandable: ({ result }) => !!result,
+ noIndent: true,
+ },
+ dataTableExportExcludedColumns: ['response', 'actions'],
+ dataTableRowsTransformer: (rows) =>
+ transformSurveyResponseRows(rows, survey),
rowProps: (record: unknown) => {
// "mute" archived records
if (typeof record !== 'object' || !record || !('result' in record)) {
diff --git a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
index d96821abc173..b8683867558f 100644
--- a/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
+++ b/frontend/src/scenes/surveys/SurveyViewRedesign/SurveyViewRedesign.tsx
@@ -38,6 +38,7 @@ import { SurveyNoResponsesBanner } from 'scenes/surveys/SurveyNoResponsesBanner'
import { getSurveyStatus, isSurveyDraft, surveysLogic } from 'scenes/surveys/surveysLogic'
import { SurveySQLHelper } from 'scenes/surveys/SurveySQLHelper'
import { SurveyStatsSummary } from 'scenes/surveys/SurveyStatsSummary'
+import { transformSurveyResponseRows } from 'scenes/surveys/utils'
import { canUseSurveyWizard } from 'scenes/surveys/utils'
import { urls } from 'scenes/urls'
@@ -696,14 +697,17 @@ function SurveyResponsesContent(): JSX.Element {
aria-busy={isRefreshingResults}
className={
isRefreshingResults
- ? 'survey-table-results opacity-75 transition-opacity duration-200 ease-out'
- : 'survey-table-results opacity-100 transition-opacity duration-200 ease-out'
+ ? 'survey-table-results space-y-4 opacity-75 transition-opacity duration-200 ease-out'
+ : 'survey-table-results space-y-4 opacity-100 transition-opacity duration-200 ease-out'
}
>
+ <SurveyStatsSummary />
<Query
query={dataTableQuery}
context={{
columns: surveyColumnRenderers,
+ dataTableExportExcludedColumns: ['response', 'actions'],
+ dataTableRowsTransformer: (rows) => transformSurveyResponseRows(rows, survey),
rowProps: (record: unknown) => {
if (typeof record !== 'object' || !record || !('result' in record)) {
return {}
diff --git a/frontend/src/scenes/surveys/components/StackedBar.tsx b/frontend/src/scenes/surveys/components/StackedBar.tsx
index 857d03d849df..44497adcea79 100644
--- a/frontend/src/scenes/surveys/components/StackedBar.tsx
+++ b/frontend/src/scenes/surveys/components/StackedBar.tsx
@@ -130,7 +130,7 @@ export function StackedBar({
})}
</div>
<div className="w-full flex justify-center">
- <div className="flex items-center gap-8">
+ <div className="flex flex-wrap justify-center items-center gap-x-8 gap-y-2">
{segments.map(
({ count, label, colorClass }) =>
count > 0 && (
diff --git a/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx b/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx
index 78f41e783b5b..87feb6436d6c 100644
--- a/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx
+++ b/frontend/src/scenes/surveys/hooks/useSurveyResponseColumns.tsx
@@ -2,14 +2,16 @@ import { useValues } from 'kea'
import { useMemo } from 'react'
import { IconLlmAnalytics, IconThumbsDown, IconThumbsUp } from '@posthog/icons'
-import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { surveyLogic } from 'scenes/surveys/surveyLogic'
-import { getSurveyResponse, isScaleTwoRating } from 'scenes/surveys/utils'
+import { getSurveyResponseStatus, isScaleTwoRating } from 'scenes/surveys/utils'
import { urls } from 'scenes/urls'
+import { EventRowActions } from '~/queries/nodes/DataTable/EventRowActions'
import { QueryContextColumn } from '~/queries/types'
-import { SurveyQuestionType } from '~/types'
+import { EventType } from '~/types'
const getTraceIdFromRecord = (record: unknown): string | null => {
if (!Array.isArray(record)) {
@@ -39,20 +41,34 @@ export function useSurveyResponseColumns(): Record<string, QueryContextColumn> {
const { survey } = useValues(surveyLogic)
return useMemo(() => {
- const columns: Record<string, QueryContextColumn> = {}
+ const columns: Record<string, QueryContextColumn> = {
+ status: {
+ title: 'Status',
+ render: ({ record }) => {
+ const event = (record as EventType[])[0]
+ const status = getSurveyResponseStatus(event.event, event.properties)
+ return (
+ <LemonTag type={status ? 'warning' : 'success'} size="small">
+ {status || 'Completed'}
+ </LemonTag>
+ )
+ },
+ },
+ respondent: {
+ title: 'Person',
+ render: ({ record }) => <PersonDisplay person={(record as EventType[])[0].person} />,
+ },
+ actions: {
+ title: ' ',
+ render: ({ record }) => <EventRowActions event={(record as EventType[])[0]} />,
+ },
+ }
survey.questions.forEach((question, index) => {
const isThumb = isScaleTwoRating(question)
const isFirstQuestion = index === 0
- const baseExpression = getSurveyResponse(question, index)
- // Must match the column expression built in surveyLogic.tsx so multi-choice
- // questions (wrapped in arrayStringConcat) also get matched.
- const columnName =
- question.type === SurveyQuestionType.MultipleChoice
- ? `arrayStringConcat(${baseExpression}, ', ')`
- : baseExpression
-
- columns[columnName] = {
+ columns[`answer_${index}`] = {
+ title: question.question || `Question ${index + 1}`,
render: ({ value, record }) => {
const traceId = isFirstQuestion ? getTraceIdFromRecord(record) : null
const stringValue = value == null ? '' : String(value)
diff --git a/frontend/src/scenes/surveys/surveyLogic.test.ts b/frontend/src/scenes/surveys/surveyLogic.test.ts
index d1975272a0c7..cd7a26bb3290 100644
--- a/frontend/src/scenes/surveys/surveyLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveyLogic.test.ts
@@ -12,6 +12,7 @@ import {
import { OpenEndedColumnMap } from 'scenes/surveys/utils'
import { useMocks } from '~/mocks/jest'
+import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import {
AccessControlLevel,
@@ -1300,20 +1301,35 @@ describe('survey filters', () => {
propertyFilters: propertyFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- {
- key: 'email',
- value: '[email protected]',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ {
+ key: 'email',
+ value: '[email protected]',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ ]),
+ }),
}),
}),
})
})
- it('collapses newlines in question text so the generated HogQL select stays single-line', async () => {
+ it.each([true, false])('merges all captured responses with partial collection set to %s', async (enabled) => {
+ await expectLogic(logic, () => {
+ logic.actions.loadSurveySuccess({ ...MULTIPLE_CHOICE_SURVEY, enable_partial_responses: enabled })
+ }).toDispatchActions(['loadSurveySuccess'])
+ const source = logic.values.dataTableQuery?.source
+ expect(source).toMatchObject({ kind: NodeKind.HogQLQuery })
+ const query = (source as { query: string }).query
+ expect(query).toContain('GROUP BY submission_key')
+ expect(query).toContain("'survey dismissed', 'survey abandoned'")
+ expect(query).toContain('argMaxIf(')
+ expect(query).not.toContain('HAVING countIf(is_completed_event) > 0')
+ })
+
+ 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
// whose text spans multiple lines used to leak past the `--` comment appended per response
// column, turning the trailing (often accented) text into invalid HogQL.
@@ -1333,11 +1349,9 @@ describe('survey filters', () => {
logic.actions.loadSurveySuccess(surveyWithMultilineQuestion)
}).toDispatchActions(['loadSurveySuccess'])
- const select = (logic.values.dataTableQuery as unknown as { source: { select: string[] } }).source.select
- // The question text is still used as the column comment...
- expect(select.some((col) => col.includes('Déjanos'))).toBe(true)
- // ...but every generated column expression is single-line, so the `--` comment can't leak.
- select.forEach((col) => expect(col).not.toMatch(/[\r\n]/))
+ const query = (logic.values.dataTableQuery?.source as { query: string }).query
+ expect(query).not.toContain('Déjanos')
+ expect(query).toContain('AS answer_0')
})
it('updates query filters when property filters change', async () => {
@@ -1360,14 +1374,16 @@ describe('survey filters', () => {
propertyFilters: initialFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- {
- key: 'email',
- value: '[email protected]',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ {
+ key: 'email',
+ value: '[email protected]',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ ]),
+ }),
}),
}),
})
@@ -1390,14 +1406,16 @@ describe('survey filters', () => {
propertyFilters: updatedFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- {
- key: 'country',
- value: 'US',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ {
+ key: 'country',
+ value: 'US',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ ]),
+ }),
}),
}),
})
@@ -1428,20 +1446,22 @@ describe('survey filters', () => {
propertyFilters: multipleFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- {
- key: 'email',
- value: '[email protected]',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- {
- key: 'country',
- value: 'US',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ {
+ key: 'email',
+ value: '[email protected]',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ {
+ key: 'country',
+ value: 'US',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ ]),
+ }),
}),
}),
})
@@ -1474,22 +1494,24 @@ describe('survey filters', () => {
propertyFilters: groupPropertyFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- {
- key: 'name',
- value: 'ACME Corp',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Group,
- group_type_index: 0,
- },
- {
- key: 'industry',
- value: 'technology',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Group,
- group_type_index: 0,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ {
+ key: 'name',
+ value: 'ACME Corp',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Group,
+ group_type_index: 0,
+ },
+ {
+ key: 'industry',
+ value: 'technology',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Group,
+ group_type_index: 0,
+ },
+ ]),
+ }),
}),
}),
})
@@ -1521,21 +1543,23 @@ describe('survey filters', () => {
propertyFilters: mixedFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- {
- key: 'email',
- value: '[email protected]',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- {
- key: 'company_name',
- value: 'ACME Corp',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Group,
- group_type_index: 0,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ {
+ key: 'email',
+ value: '[email protected]',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ {
+ key: 'company_name',
+ value: 'ACME Corp',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Group,
+ group_type_index: 0,
+ },
+ ]),
+ }),
}),
}),
})
@@ -1560,22 +1584,17 @@ describe('survey filters', () => {
propertyFilters: propertyFilters,
dataTableQuery: partial({
source: partial({
- properties: expect.arrayContaining([
- // Survey ID property should still be present
- {
- key: SurveyEventProperties.SURVEY_ID,
- operator: 'exact',
- type: 'event',
- value: MULTIPLE_CHOICE_SURVEY.id,
- },
- // Our new filter should be present
- {
- key: 'email',
- value: '[email protected]',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Person,
- },
- ]),
+ filters: partial({
+ properties: expect.arrayContaining([
+ // Our new filter should be present
+ {
+ key: 'email',
+ value: '[email protected]',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ },
+ ]),
+ }),
}),
}),
})
@@ -1591,15 +1610,8 @@ describe('survey filters', () => {
propertyFilters: [],
dataTableQuery: partial({
source: partial({
- // Should still have the survey ID property even with no filters
- properties: expect.arrayContaining([
- {
- key: SurveyEventProperties.SURVEY_ID,
- operator: 'exact',
- type: 'event',
- value: MULTIPLE_CHOICE_SURVEY.id,
- },
- ]),
+ filters: { properties: [] },
+ query: expect.stringContaining(MULTIPLE_CHOICE_SURVEY.id),
}),
}),
})
@@ -1877,6 +1889,7 @@ describe('survey stats calculation', () => {
logic.actions.setDismissedAndSentCount(null)
}).toMatchValues({
processedSurveyStats: null,
+ surveyResponseOutcomes: null,
surveyRates: {
response_rate: 0.0,
dismissal_rate: 0.0,
@@ -1886,6 +1899,25 @@ describe('survey stats calculation', () => {
})
})
+ it.each([true, false])(
+ 'uses submissions for outcome percentages when counting people is %s',
+ async (countPeople) => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilterSurveyStatsByDistinctId(countPeople)
+ logic.actions.setBaseStatsResults([
+ createBaseStat(SurveyEventName.SHOWN, 100, 80),
+ [SurveyEventName.SENT, 5, 1, MOCK_FIRST_SEEN, MOCK_LAST_SEEN, [2, 1, 2]],
+ ])
+ }).toMatchValues({
+ surveyResponseOutcomes: [
+ { label: 'Completed', count: 2, percentage: 0.4 },
+ { label: 'Dismissed', count: 1, percentage: 0.2 },
+ { label: 'Abandoned', count: 2, percentage: 0.4 },
+ ],
+ })
+ }
+ )
+
it('should calculate stats correctly when only "survey shown" events exist', async () => {
const baseStats = [createBaseStat(SurveyEventName.SHOWN, 100, 80)]
const expectedStats: SurveyStats = {
diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsx
index dea3a2e0b0ea..a7aba641feaa 100644
--- a/frontend/src/scenes/surveys/surveyLogic.tsx
+++ b/frontend/src/scenes/surveys/surveyLogic.tsx
@@ -132,17 +132,19 @@ import {
DATE_FORMAT,
type OpenEndedColumnMap,
type SurveyQueryFilters,
+ type SurveyResponseOutcome,
buildAggregateQuery,
buildOpenEndedQuery,
- buildPartialResponsesFilter,
+ buildSurveyResponsesQuery,
+ buildSurveyResponseStatsQuery,
+ buildSurveyRespondentQuery,
buildSurveyOptionalBooleanPropertyFilter,
buildSurveyTimestampFilter,
calculateSurveyRates,
createAnswerFilterHogQLExpression,
- getExpressionCommentForQuestion,
getResponseFieldWithId,
getSurveyEndDateForQuery,
- getSurveyResponse,
+ getSurveyResponseOutcomeBreakdown,
getSurveyStartDateForQuery,
isSurveyRunning,
isThumbQuestion,
@@ -151,7 +153,14 @@ import {
validateSurveyAppearance,
} from './utils'
-export type SurveyBaseStatTuple = [string, number, number, string | null, string | null] // [event_name, total_count, unique_persons, first_seen, last_seen]
+export type SurveyBaseStatTuple = [
+ eventName: string,
+ totalCount: number,
+ uniquePersons: number,
+ firstSeen: string | null,
+ lastSeen: string | null,
+ outcomeCounts?: [number, number, number],
+] // [event_name, total_count, unique_persons, first_seen, last_seen, outcome_counts]
export type SurveyBaseStatsResult = SurveyBaseStatTuple[] | null
export type DismissedAndSentCountResult = number | null
export type TranslationValidationError = {
@@ -703,7 +712,6 @@ export interface surveyLogicValues {
isSurveyRunning: boolean
isSurveySubmitting: boolean
isSurveyValid: boolean
- partialResponsesFilter: string
personNames: Record<string, string>
processedSurveyStats: SurveyStats | null
projectTreeRef: ProjectTreeRef
@@ -743,6 +751,7 @@ export interface surveyLogicValues {
surveyNotificationsLoading: boolean
surveyRates: SurveyRates | null
surveyRepeatedActivationAvailable: boolean
+ surveyResponseOutcomes: SurveyResponseOutcome[] | null
surveyShufflingQuestionsAvailable: boolean
surveyTouched: boolean
surveyTouches: Record<string, boolean>
@@ -1370,7 +1379,6 @@ export interface surveyLogicMeta {
personNames: Record<string, string>
) => ConsolidatedSurveyResults
timestampFilter: (survey: NewSurvey | Survey, dateRange: SurveyDateRange | null) => string
- partialResponsesFilter: (survey: NewSurvey | Survey, dateRange: SurveyDateRange | null) => string
archivedResponsesFilter: (showArchivedResponses: boolean, archivedResponseUuids: Set<string>) => string
archivedResponsesPropertyFilter: (
showArchivedResponses: boolean,
@@ -1417,12 +1425,9 @@ export interface surveyLogicMeta {
dataTableQuery: (
survey: NewSurvey | Survey,
propertyFilters: AnyPropertyFilter[],
- answerFilterHogQLExpression: string,
- partialResponsesFilter: string,
- archivedResponsesFilter: string,
- dateRange: SurveyDateRange | null,
- archivedResponseUuids: Set<string>,
- showArchivedResponses: boolean
+ answerFilters: EventPropertyFilter[],
+ timestampFilter: string,
+ archivedResponsesFilter: string
) => DataTableNode | null
targetingFlagFilters: (survey: NewSurvey | Survey) => FeatureFlagFilters | undefined
urlMatchTypeValidationError: (survey: NewSurvey | Survey) => string | null
@@ -1458,6 +1463,7 @@ export interface surveyLogicMeta {
) => (questionIndex: number, fieldPath: string) => TranslationValidationError | undefined
surveyAsInsightURL: (survey: NewSurvey | Survey) => string
defaultInterval: (survey: NewSurvey | Survey) => IntervalType
+ surveyResponseOutcomes: (surveyBaseStatsInternal: SurveyBaseStatsResult) => SurveyResponseOutcome[] | null
processedSurveyStats: (
surveyBaseStatsInternal: SurveyBaseStatsResult,
surveyDismissedAndSentCountInternal: DismissedAndSentCountResult
@@ -1746,47 +1752,27 @@ export const surveyLogic = kea<surveyLogicType>([
if (props.id === NEW_SURVEY.id || !values.survey?.start_date) {
return null
}
- // if we have answer filters, we need to apply them to the query for the 'survey sent' event only
- const answerFilterCondition = values.answerFilterHogQLExpression
- ? values.answerFilterHogQLExpression.slice(4)
- : '1=1' // Use '1=1' for SQL TRUE
-
+ const responseStats = buildSurveyResponseStatsQuery(values.survey as Survey, {
+ timestampFilter: values.timestampFilter,
+ answerFilters: values.answerFilters,
+ archivedResponsesFilter: values.archivedResponsesFilter,
+ })
const query = `
-- QUERYING BASE STATS
- SELECT
- event as event_name,
- count() as total_count,
+ SELECT event as event_name, count() as total_count,
count(DISTINCT person_id) as unique_persons,
- if(count() > 0, min(timestamp), null) as first_seen,
- if(count() > 0, max(timestamp), null) as last_seen
+ min(timestamp) as first_seen, max(timestamp) as last_seen,
+ tuple(0, 0, 0) as outcome_counts
FROM events
- WHERE team_id = ${teamLogic.values.currentTeamId}
- AND event IN ('${SurveyEventName.SHOWN}', '${SurveyEventName.DISMISSED}', '${SurveyEventName.SENT}')
+ WHERE event IN ('${SurveyEventName.SHOWN}', '${SurveyEventName.DISMISSED}')
AND properties.\`${SurveyEventProperties.SURVEY_ID}\` = '${props.id}'
${values.timestampFilter}
${values.archivedResponsesFilter}
- AND {filters} -- Apply property filters here to the main query
- -- Main condition for handling partial responses and answer filters:
- AND (
- event != '${SurveyEventName.DISMISSED}'
- OR
- ${buildSurveyOptionalBooleanPropertyFilter(
- SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED,
- 'true'
- )}
- )
- AND (
- -- Include non-'sent' events directly
- event != '${SurveyEventName.SENT}'
- OR
- -- Include 'sent' events only if they meet the outer query's answer filter AND are in the unique list (old or latest partial/complete)
- (
- (${answerFilterCondition}) -- Apply answer filters ONLY to 'sent' events in the outer query
- -- Check if the event's UUID is in the list generated by the subquery
- ${values.partialResponsesFilter}
- )
- )
- GROUP BY event` as HogQLQueryString
+ AND {filters}
+ AND (event != '${SurveyEventName.DISMISSED}' OR ${buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED, 'true')})
+ GROUP BY event
+ UNION ALL
+ ${responseStats}` as HogQLQueryString
const response = await api.queryHogQL(query, SURVEY_QUERY_TAGS.baseStats, {
queryParams: {
@@ -1806,36 +1792,22 @@ export const surveyLogic = kea<surveyLogicType>([
if (props.id === NEW_SURVEY.id || !values.survey?.start_date) {
return null
}
- // if we have answer filters, we need to apply them to the query for the 'survey sent' event only
- const answerFilterCondition =
- values.answerFilterHogQLExpression === ''
- ? '1=1' // Use '1=1' for SQL TRUE
- : values.answerFilterHogQLExpression.substring(4)
-
+ const respondents = buildSurveyRespondentQuery(values.survey as Survey, {
+ timestampFilter: values.timestampFilter,
+ answerFilters: values.answerFilters,
+ archivedResponsesFilter: values.archivedResponsesFilter,
+ })
const query = `
-- QUERYING DISMISSED AND SENT COUNT
- SELECT count()
- FROM (
- SELECT person_id
- FROM events
- WHERE team_id = ${teamLogic.values.currentTeamId}
- AND event IN ('${SurveyEventName.DISMISSED}', '${SurveyEventName.SENT}')
- AND properties.\`${SurveyEventProperties.SURVEY_ID}\` = '${props.id}'
- ${values.timestampFilter}
- ${values.archivedResponsesFilter}
- AND (
- event != '${SurveyEventName.DISMISSED}'
- OR
- ${buildSurveyOptionalBooleanPropertyFilter(
- SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED,
- 'true'
- )}
- )
- AND {filters} -- Apply property filters here to reduce initial events
- GROUP BY person_id
- HAVING sum(if(event = '${SurveyEventName.DISMISSED}', 1, 0)) > 0 -- Has at least one dismissed event (matching property filters)
- AND sum(if(event = '${SurveyEventName.SENT}' AND (${answerFilterCondition}), 1, 0)) > 0 -- Has at least one sent event matching BOTH property and answer filters
- ) AS PersonsWithBothEvents` as HogQLQueryString
+ SELECT count(DISTINCT person_id)
+ FROM events
+ WHERE event = '${SurveyEventName.DISMISSED}'
+ AND properties.\`${SurveyEventProperties.SURVEY_ID}\` = '${props.id}'
+ ${values.timestampFilter}
+ ${values.archivedResponsesFilter}
+ AND ${buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED, 'true')}
+ AND {filters}
+ AND person_id IN (${respondents})` as HogQLQueryString
const response = await api.queryHogQL(query, SURVEY_QUERY_TAGS.dismissedAndSent, {
queryParams: {
@@ -2840,23 +2812,6 @@ export const surveyLogic = kea<surveyLogicType>([
return buildSurveyTimestampFilter(survey, dateRange)
},
],
- partialResponsesFilter: [
- (s) => [s.survey, s.dateRange],
- (survey: Survey, dateRange: SurveyDateRange): string => {
- if (survey.enable_partial_responses) {
- return buildPartialResponsesFilter(survey, dateRange)
- }
- /**
- * Return only complete responses. For pre-partial responses, we didn't have the survey_completed property.
- * So we return all responses that don't have it.
- * For posthog-js > 1.240, we use the $survey_completed property.
- */
- return `AND ${buildSurveyOptionalBooleanPropertyFilter(
- SurveyEventProperties.SURVEY_COMPLETED,
- 'false'
- )}`
- },
- ],
archivedResponsesFilter: [
(s) => [s.showArchivedResponses, s.archivedResponseUuids],
(showArchivedResponses: boolean, archivedUuids: Set<string>): string => {
@@ -3080,82 +3035,36 @@ export const surveyLogic = kea<surveyLogicType>([
},
],
dataTableQuery: [
- (s) => [
- s.survey,
- s.propertyFilters,
- s.answerFilterHogQLExpression,
- s.partialResponsesFilter,
- s.archivedResponsesFilter,
- s.dateRange,
- s.archivedResponseUuids,
- s.showArchivedResponses,
- ],
+ (s) => [s.survey, s.propertyFilters, s.answerFilters, s.timestampFilter, s.archivedResponsesFilter],
(
survey: Survey,
propertyFilters: AnyPropertyFilter[],
- answerFilterHogQLExpression: string,
- partialResponsesFilter: string,
- archivedResponsesFilter: string,
- dateRange: SurveyDateRange
+ answerFilters: EventPropertyFilter[],
+ timestampFilter: string,
+ archivedResponsesFilter: string
): DataTableNode | null => {
if (survey.id === 'new') {
return null
}
- const startDate = getSurveyStartDateForQuery(survey)
- const endDate = getSurveyEndDateForQuery(survey)
-
- const where = [`event == '${SurveyEventName.SENT}'`, partialResponsesFilter.replace(/^AND\s+/, '')]
-
- if (answerFilterHogQLExpression !== '') {
- // skip the 'AND ' prefix
- where.push(answerFilterHogQLExpression.substring(4))
- }
-
- if (archivedResponsesFilter !== '') {
- // skip the 'AND ' prefix
- where.push(archivedResponsesFilter.substring(4))
- }
-
- const defaultColumns = [
- '*',
- ...survey.questions.map((q, i) => {
- if (q.type === SurveyQuestionType.MultipleChoice) {
- return `arrayStringConcat(${getSurveyResponse(q, i)}, ', ') -- ${getExpressionCommentForQuestion(q, i)}`
- }
- return `${getSurveyResponse(q, i)} -- ${getExpressionCommentForQuestion(q, i)}`
- }),
- 'timestamp',
- 'person',
- ]
-
return {
kind: NodeKind.DataTableNode,
source: {
- kind: NodeKind.EventsQuery,
- select: defaultColumns,
- orderBy: ['timestamp DESC'],
- where,
- after: dateRange?.date_from || startDate,
- before: dateRange?.date_to || endDate,
- properties: [
- {
- type: PropertyFilterType.Event,
- key: SurveyEventProperties.SURVEY_ID,
- operator: PropertyOperator.Exact,
- value: survey.id,
- },
- ...propertyFilters,
- ],
+ kind: NodeKind.HogQLQuery,
+ query: buildSurveyResponsesQuery(survey, {
+ answerFilters,
+ timestampFilter,
+ archivedResponsesFilter,
+ }),
+ filters: { properties: propertyFilters },
},
- defaultColumns,
- propertiesViaUrl: true,
+ hiddenColumns: ['response'],
showExport: true,
showReload: true,
+ showOpenEditorButton: false,
showRecordingColumn: false,
showEventFilter: false,
showPropertyFilter: false,
showTimings: false,
- showPersistentColumnConfigurator: true,
contextKey: `survey:${survey.id}`,
}
},
@@ -3714,6 +3623,13 @@ export const surveyLogic = kea<surveyLogicType>([
return 'month'
},
],
+ surveyResponseOutcomes: [
+ (s) => [s.surveyBaseStatsInternal],
+ (baseStats: SurveyBaseStatsResult): SurveyResponseOutcome[] | null => {
+ const counts = baseStats?.find(([eventName]) => eventName === SurveyEventName.SENT)?.[5]
+ return counts ? getSurveyResponseOutcomeBreakdown(counts) : null
+ },
+ ],
processedSurveyStats: [
(s) => [s.surveyBaseStatsInternal, s.surveyDismissedAndSentCountInternal],
(
diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.ts
index 3adcd4eb105e..8ae5ef1079e6 100644
--- a/frontend/src/scenes/surveys/utils.test.ts
+++ b/frontend/src/scenes/surveys/utils.test.ts
@@ -22,7 +22,6 @@ import {
buildAggregateQuery,
buildOpenEndedQuery,
buildSurveyExampleInvocationGlobals,
- buildPartialResponsesFilter,
buildSurveyOptionalBooleanPropertyFilter,
buildSurveyTimestampFilter,
calculateNpsBreakdown,
@@ -36,6 +35,9 @@ import {
getSurveyDisplayConditionsSummary,
getSurveyEndDateForQuery,
getSurveyResponse,
+ getSurveyResponseOutcomeBreakdown,
+ getSurveyResponseStatus,
+ transformSurveyResponseRows,
getSurveyStartDateForQuery,
isSimpleSurveyAudienceTargeting,
sanitizeColor,
@@ -60,6 +62,72 @@ afterEach(() => {
})
describe('survey utils', () => {
+ it.each<{ counts: [number, number, number]; percentages: number[] }>([
+ { counts: [2, 1, 2], percentages: [0.4, 0.2, 0.4] },
+ { counts: [0, 1, 3], percentages: [0, 0.25, 0.75] },
+ { counts: [3, 0, 0], percentages: [1, 0, 0] },
+ { counts: [0, 0, 0], percentages: [0, 0, 0] },
+ ])('calculates response outcome shares for $counts', ({ counts, percentages }) => {
+ expect(getSurveyResponseOutcomeBreakdown(counts)).toEqual(
+ ['Completed', 'Dismissed', 'Abandoned'].map((label, index) => ({
+ label,
+ count: counts[index],
+ percentage: percentages[index],
+ }))
+ )
+ })
+
+ it.each([
+ ['survey sent', { $survey_completed: false }, 'Abandoned'],
+ ['survey dismissed', { $survey_partially_completed: true }, 'Dismissed'],
+ ['survey abandoned', { $survey_partially_completed: 'true' }, 'Abandoned'],
+ ['survey sent', {}, null],
+ ['survey dismissed', { $survey_completed: true, $survey_partially_completed: true }, null],
+ ])('labels %s using completion and dismissal status', (event, properties, expected) => {
+ expect(getSurveyResponseStatus(event, properties)).toBe(expected)
+ })
+
+ it.each(['completed', 'abandoned'])('renders merged answers and the %s outcome', (outcome) => {
+ const survey = {
+ questions: [
+ { id: 'rating', type: SurveyQuestionType.Rating },
+ { id: 'text', type: SurveyQuestionType.Open },
+ ],
+ } as Survey
+ const rows = [
+ {
+ result: [
+ [
+ 'event-id',
+ 'respondent',
+ '2026-09-08T12:00:00Z',
+ 'person-id',
+ '{}',
+ JSON.stringify({
+ $survey_id: 'survey-id',
+ $survey_response_text: 'Final answer',
+ $survey_completed: false,
+ }),
+ outcome,
+ ['9', 'Final answer'],
+ SurveyEventName.SENT,
+ ],
+ ],
+ },
+ ]
+ const [row] = transformSurveyResponseRows(rows, survey)
+ expect(Array.isArray(row.result) ? row.result[0] : null).toMatchObject({
+ uuid: 'event-id',
+ event: SurveyEventName.SENT,
+ properties: {
+ $survey_response_rating: '9',
+ $survey_response_text: 'Final answer',
+ $survey_completed: outcome === 'completed',
+ $survey_partially_completed: outcome !== 'completed',
+ },
+ })
+ })
+
beforeAll(() => {
// Mock CSS.supports
global.CSS = {
@@ -1013,55 +1081,6 @@ describe('survey utils', () => {
})
})
- describe('buildPartialResponsesFilter', () => {
- it('keeps missing survey_completed values eligible for complete-response queries', () => {
- const survey = {
- id: 'test-survey-id',
- created_at: '2024-11-19T00:00:00Z',
- end_date: null,
- enable_partial_responses: false,
- } as Survey
-
- expect(buildPartialResponsesFilter(survey)).toBe(
- `AND ${buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_COMPLETED, 'false')}`
- )
- })
-
- it('uses same date bounds as buildSurveyTimestampFilter', () => {
- const survey = {
- id: 'test-survey-id',
- created_at: '2024-11-19T00:00:00Z',
- end_date: '2024-11-25T00:00:00Z',
- enable_partial_responses: true,
- } as Survey
- const dateRange = { date_from: '2024-11-20', date_to: '2024-11-22' }
-
- const timestampFilter = buildSurveyTimestampFilter(survey, dateRange)
- const partialFilter = buildPartialResponsesFilter(survey, dateRange)
-
- const fromMatch = timestampFilter.match(/timestamp >= '([^']+)'/)
- const toMatch = timestampFilter.match(/timestamp <= '([^']+)'/)
-
- expect(partialFilter).toContain(`greaterOrEquals(timestamp, '${fromMatch?.[1]}')`)
- expect(partialFilter).toContain(`lessOrEquals(timestamp, '${toMatch?.[1]}')`)
- })
-
- it('uses direct property access for fixed survey properties', () => {
- const survey = {
- id: 'test-survey-id',
- created_at: '2024-11-19T00:00:00Z',
- end_date: null,
- enable_partial_responses: true,
- } as Survey
-
- const partialFilter = buildPartialResponsesFilter(survey)
-
- expect(partialFilter).toContain('properties.`$survey_id`')
- expect(partialFilter).toContain('properties.`$survey_submission_id`')
- expect(partialFilter).not.toContain('JSONExtractString')
- })
- })
-
describe('submission merging in the results queries', () => {
const buildSurvey = (enablePartialResponses: boolean): Survey =>
({
@@ -1099,33 +1118,24 @@ describe('survey utils', () => {
const query = buildAggregateQuery(survey, buildFilters(survey))
- expect(query).toContain(`argMaxIf(q${index}_raw, timestamp, ${presenceExpr}) AS q${index}_answer`)
- expect(query).toContain('GROUP BY submission_key')
- })
-
- it('requires a completed event per submission rather than per event when partial responses are off', () => {
- const survey = buildSurvey(false)
-
- const query = buildAggregateQuery(survey, buildFilters(survey))
-
- // The completed check has to run over the grouped submission. Back in the event-level
- // WHERE it removes the partial events before their answers can be merged, which is
- // exactly how a rating sent on its own event went missing.
- expect(query).toContain('HAVING countIf(is_completed_event) > 0')
expect(query).toContain(
- `${buildSurveyOptionalBooleanPropertyFilter(
- SurveyEventProperties.SURVEY_COMPLETED,
- 'false'
- )} AS is_completed_event`
+ `argMaxIf(q${index}_raw, tuple(timestamp, event_uuid), ${presenceExpr}) AS q${index}_answer`
)
+ expect(query).toContain('GROUP BY submission_key')
})
- it('surfaces every submission regardless of completion when partial responses are on', () => {
- const survey = buildSurvey(true)
-
- const query = buildAggregateQuery(survey, buildFilters(survey))
-
- expect(query).not.toContain('is_completed_event')
+ it.each([true, false])('includes captured answers with partial collection set to %s', (enabled) => {
+ const survey = buildSurvey(enabled)
+ for (const query of [
+ buildAggregateQuery(survey, buildFilters(survey)),
+ buildOpenEndedQuery(survey, buildFilters(survey))?.query,
+ ]) {
+ expect(query).toContain("event = 'survey sent'")
+ expect(query).toContain("'survey dismissed', 'survey abandoned'")
+ expect(query).toContain(SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED)
+ expect(query).toContain('GROUP BY submission_key')
+ expect(query).not.toContain('HAVING countIf(is_completed_event) > 0')
+ }
})
it('applies answer and archive filters to the merged answer, not to single events', () => {
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index 870b415329cc..5aa3823da508 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -14,11 +14,13 @@ import {
} from 'scenes/surveys/constants'
import { SurveyRatingResults } from 'scenes/surveys/surveyLogic'
+import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import {
BasicSurveyQuestion,
CyclotronJobInvocationGlobals,
CyclotronJobFiltersType,
EventPropertyFilter,
+ EventType,
FeatureFlagFilters,
LinkSurveyQuestion,
MultipleSurveyQuestion,
@@ -665,31 +667,11 @@ export function buildSurveyOptionalBooleanPropertyFilter(
return `coalesce(JSONExtractString(properties, '${propertyName}'), '') != '${excludedValue}'`
}
-export function buildPartialResponsesFilter(survey: Survey, dateRange?: SurveyDateRange | null): string {
- if (!survey.enable_partial_responses) {
- return `AND ${buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_COMPLETED, 'false')}`
- }
-
- const { fromDate, toDate } = getResolvedSurveyDateRange(survey, dateRange)
-
- return `AND uuid in (
- SELECT
- argMax(uuid, timestamp)
- FROM events
- WHERE and(
- equals(event, '${SurveyEventName.SENT}'),
- equals(properties.\`${SurveyEventProperties.SURVEY_ID}\`, '${survey.id}'),
- greaterOrEquals(timestamp, '${fromDate}'),
- lessOrEquals(timestamp, '${toDate}')
- )
- GROUP BY
- if(
- isNotNull(properties.\`${SurveyEventProperties.SURVEY_SUBMISSION_ID}\`)
- AND properties.\`${SurveyEventProperties.SURVEY_SUBMISSION_ID}\` != '',
- properties.\`${SurveyEventProperties.SURVEY_SUBMISSION_ID}\`,
- toString(uuid)
- )
- ) --- Filter to ensure we only get one response per ${SurveyEventProperties.SURVEY_SUBMISSION_ID}`
+export function buildSurveyResponseEventFilter(): string {
+ return `(event = '${SurveyEventName.SENT}' OR (
+ event IN ('${SurveyEventName.DISMISSED}', '${SurveyEventName.ABANDONED}')
+ AND coalesce(JSONExtractString(properties, '${SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED}'), '') = 'true'
+ ))`
}
export interface SurveyQueryFilters {
@@ -699,7 +681,7 @@ export interface SurveyQueryFilters {
}
/**
- * HogQL expression collapsing a submission's `survey sent` events into one group. An event with
+ * HogQL expression collapsing a submission's response events into one group. An event with
* no `$survey_submission_id` is keyed by its own uuid, so it stays a distinct response the way it
* did before submission IDs existed.
*
@@ -765,32 +747,45 @@ function buildMergedSubmissionsSubquery(
questions: QuestionWithIndex[],
{ includeRespondentMetadata = false }: { includeRespondentMetadata?: boolean } = {}
): string {
- // With partial responses off, only completed submissions may surface. That check has to run
- // against the whole submission rather than a single event, because the answers still need
- // merging from the partial events that led up to the completed one.
- const requiresCompletedEvent = !survey.enable_partial_responses
- const completedEventExpr = buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_COMPLETED, 'false')
+ const completedEventExpr = `event = '${SurveyEventName.SENT}' AND ${buildSurveyOptionalBooleanPropertyFilter(SurveyEventProperties.SURVEY_COMPLETED, 'false')}`
const innerColumns = [
- 'uuid',
+ 'uuid AS event_uuid',
'timestamp',
- ...(includeRespondentMetadata ? ['distinct_id', 'properties.`$session_id` AS session_id'] : []),
- ...(requiresCompletedEvent ? [`${completedEventExpr} AS is_completed_event`] : []),
+ 'person_id',
+ ...(includeRespondentMetadata
+ ? [
+ 'distinct_id',
+ 'properties.`$session_id` AS session_id',
+ 'properties AS event_properties',
+ 'person.properties AS person_properties',
+ ]
+ : []),
+ `${completedEventExpr} AS is_completed_event`,
+ 'event',
...questions.map(({ question, index }) => `${getSurveyResponse(question, index)} AS ${rawAnswerAlias(index)}`),
`${SUBMISSION_GROUPING_KEY} AS submission_key`,
]
const outerColumns = [
- 'argMax(uuid, timestamp) AS uuid',
+ 'argMax(event_uuid, tuple(timestamp, event_uuid)) AS uuid',
+ 'argMax(person_id, tuple(timestamp, event_uuid)) AS person_id',
+ `if(countIf(is_completed_event) > 0, 'completed', if(argMax(event, tuple(timestamp, event_uuid)) = '${SurveyEventName.DISMISSED}', 'dismissed', 'abandoned')) AS outcome`,
// Aliased away from `timestamp` because every other aggregate here orders by that column,
// and an alias of the same name would resolve to this aggregate instead, nesting them.
'max(timestamp) AS submitted_at',
...(includeRespondentMetadata
- ? ['argMax(distinct_id, timestamp) AS distinct_id', 'argMax(session_id, timestamp) AS session_id']
+ ? [
+ 'argMax(distinct_id, tuple(timestamp, event_uuid)) AS distinct_id',
+ 'argMax(session_id, tuple(timestamp, event_uuid)) AS session_id',
+ 'argMax(event_properties, tuple(timestamp, event_uuid)) AS event_properties',
+ 'argMax(person_properties, tuple(timestamp, event_uuid)) AS person_properties',
+ 'argMax(event, tuple(timestamp, event_uuid)) AS latest_event',
+ ]
: []),
...questions.map(({ question, index }) => {
const raw = rawAnswerAlias(index)
- return `argMaxIf(${raw}, timestamp, ${buildAnswerPresenceExpr(raw, question)}) AS ${mergedAnswerAlias(index)}`
+ return `argMaxIf(${raw}, tuple(timestamp, event_uuid), ${buildAnswerPresenceExpr(raw, question)}) AS ${mergedAnswerAlias(index)}`
}),
]
@@ -798,9 +793,6 @@ function buildMergedSubmissionsSubquery(
// filter names `uuid`, which resolves to the representative uuid aliased above — the same one
// the responses table archives.
const havingConditions: string[] = []
- if (requiresCompletedEvent) {
- havingConditions.push('countIf(is_completed_event) > 0')
- }
const mergedAnswerFilter = createAnswerFilterHogQLExpression(filters.answerFilters, survey, (_, index) =>
mergedAnswerAlias(index)
)
@@ -815,7 +807,7 @@ function buildMergedSubmissionsSubquery(
FROM (
SELECT ${innerColumns.join(',\n ')}
FROM events
- WHERE event = '${SurveyEventName.SENT}'
+ WHERE ${buildSurveyResponseEventFilter()}
AND properties.\`${SurveyEventProperties.SURVEY_ID}\` = '${survey.id}'
${filters.timestampFilter}
AND {filters}
@@ -823,6 +815,150 @@ function buildMergedSubmissionsSubquery(
GROUP BY submission_key${havingConditions.length > 0 ? `\n HAVING ${havingConditions.join(' AND ')}` : ''}`
}
+export function getSurveyResponseStatus(
+ eventName: string | undefined,
+ properties: Record<string, unknown>
+): string | null {
+ const completed = properties[SurveyEventProperties.SURVEY_COMPLETED]
+ if (completed === true || completed === 'true') {
+ return null
+ }
+ const partial = properties[SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED]
+ if (completed !== false && completed !== 'false' && partial !== true && partial !== 'true') {
+ return null
+ }
+ if (eventName === SurveyEventName.DISMISSED) {
+ return 'Dismissed'
+ }
+ return 'Abandoned'
+}
+
+export function isSurveyResponseEvent(eventName: string, properties: Record<string, unknown>): boolean {
+ return (
+ !!properties[SurveyEventProperties.SURVEY_ID] &&
+ (eventName === SurveyEventName.SENT ||
+ (([SurveyEventName.DISMISSED, SurveyEventName.ABANDONED] as string[]).includes(eventName) &&
+ [true, 'true'].includes(
+ properties[SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED] as boolean | string
+ )))
+ )
+}
+
+export function transformSurveyResponseRows(rows: DataTableRow[], survey: Pick<Survey, 'questions'>): DataTableRow[] {
+ return rows.map((row) => {
+ if (!Array.isArray(row.result) || !Array.isArray(row.result[0])) {
+ return row
+ }
+ const [
+ uuid,
+ distinctId,
+ timestamp,
+ personId,
+ personProperties,
+ eventProperties,
+ outcome,
+ answers,
+ latestEvent,
+ ] = row.result[0]
+ const properties = { ...JSON.parse(eventProperties || '{}') }
+ survey.questions.forEach((question, index) => {
+ const answer = answers[index]
+ if (answer !== null && answer !== undefined) {
+ properties[getSurveyResponseKey(index)] = answer
+ if (question.id) {
+ properties[`$survey_response_${question.id}`] = answer
+ }
+ }
+ })
+ properties[SurveyEventProperties.SURVEY_COMPLETED] = outcome === 'completed'
+ properties[SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED] = outcome !== 'completed'
+ const event: EventType = {
+ id: uuid,
+ uuid,
+ distinct_id: distinctId,
+ timestamp,
+ event: outcome === 'completed' ? SurveyEventName.SENT : latestEvent,
+ properties,
+ person_id: personId,
+ person: {
+ is_identified: false,
+ distinct_ids: [distinctId],
+ properties: JSON.parse(personProperties || '{}'),
+ },
+ elements: [],
+ }
+ return { ...row, result: [event, ...row.result.slice(1)] }
+ })
+}
+
+export function buildSurveyResponsesQuery(survey: Survey, filters: SurveyQueryFilters): string {
+ const questions = getAnswerableQuestions(survey)
+ const merged = buildMergedSubmissionsSubquery(survey, filters, questions, { includeRespondentMetadata: true })
+ const answers = survey.questions.map((question, index) =>
+ question.type !== SurveyQuestionType.Link ? mergedAnswerAlias(index) : 'NULL'
+ )
+ const columns = [
+ `tuple(uuid, distinct_id, submitted_at, person_id, person_properties, event_properties, outcome, tuple(${answers.length ? answers.join(', ') : 'NULL'}), latest_event) AS response`,
+ ...survey.questions.map(
+ (question, index) =>
+ `${question.type === SurveyQuestionType.MultipleChoice ? `arrayStringConcat(${answers[index]}, ', ')` : answers[index]} AS answer_${index}`
+ ),
+ 'outcome AS status',
+ 'submitted_at AS timestamp',
+ 'distinct_id AS respondent',
+ 'uuid AS actions',
+ ]
+ return `SELECT ${columns.join(',\n')} FROM (${merged}) ORDER BY submitted_at DESC`
+}
+
+export function buildSurveyResponseSQLQuery(
+ survey: Survey,
+ filters: SurveyQueryFilters,
+ questionIndex?: number
+): string {
+ const merged = buildMergedSubmissionsSubquery(survey, filters, getAnswerableQuestions(survey), {
+ includeRespondentMetadata: true,
+ }).replaceAll('{filters}', '1 = 1')
+ const columns = survey.questions.flatMap((question, index) => {
+ if (question.type === SurveyQuestionType.Link || (questionIndex !== undefined && index !== questionIndex)) {
+ return []
+ }
+ const title = (question.question || `Question ${index + 1}`).replace(/\s*[\r\n]+\s*/g, ' ').replace(/"/g, '""')
+ return [`${mergedAnswerAlias(index)} AS "${title}"`]
+ })
+ return `SELECT distinct_id, ${columns.length ? columns.join(', ') + ', ' : ''}outcome, submitted_at
+ FROM (${merged}) ORDER BY submitted_at DESC LIMIT 100`
+}
+
+export function buildSurveyResponseStatsQuery(survey: Survey, filters: SurveyQueryFilters): string {
+ const merged = buildMergedSubmissionsSubquery(survey, filters, getAnswerableQuestions(survey))
+ return `SELECT '${SurveyEventName.SENT}' AS event_name, count() AS total_count,
+ count(DISTINCT person_id) AS unique_persons,
+ if(count() > 0, min(submitted_at), null) AS first_seen,
+ if(count() > 0, max(submitted_at), null) AS last_seen,
+ tuple(countIf(outcome = 'completed'), countIf(outcome = 'dismissed'), countIf(outcome = 'abandoned')) AS outcome_counts
+ FROM (${merged})`
+}
+
+export interface SurveyResponseOutcome {
+ label: string
+ count: number
+ percentage: number
+}
+
+export function getSurveyResponseOutcomeBreakdown(counts: [number, number, number]): SurveyResponseOutcome[] {
+ const total = counts.reduce((sum, count) => sum + count, 0)
+ return ['Completed', 'Dismissed', 'Abandoned'].map((label, index) => ({
+ label,
+ count: counts[index],
+ percentage: total > 0 ? counts[index] / total : 0,
+ }))
+}
+
+export function buildSurveyRespondentQuery(survey: Survey, filters: SurveyQueryFilters): string {
+ return `SELECT person_id FROM (${buildMergedSubmissionsSubquery(survey, filters, getAnswerableQuestions(survey))})`
+}
+
function stripLeadingAnd(expression: string): string {
return expression.replace(/^\s*AND\s+/, '')
}
@@ -831,7 +967,7 @@ function stripLeadingAnd(expression: string): string {
function getAnswerableQuestions(survey: Survey): QuestionWithIndex[] {
return survey.questions
.map((question, index) => ({ question, index }))
- .filter(({ question }) => !!question.id && question.type !== SurveyQuestionType.Link)
+ .filter(({ question }) => question.type !== SurveyQuestionType.Link)
}
export interface OpenEndedColumnMap {
@@ -1394,9 +1530,8 @@ export function surveyEmitsPartialSentEvents(survey: Pick<Survey, 'type' | 'enab
/**
* Without intermediate partial events, posthog-js has no partial submission to distinguish a
* complete one from, so it never sets `$survey_completed` and requiring `= true` matches nothing.
- * Accept the property being absent as completed too, the same way the response summary counts them
- * (`enable_partial_responses` branch in `ee/surveys/summaries/headline_summary.py`). An explicit
- * `false` stays excluded: a survey switched from partial to non-partial keeps its old partials.
+ * Accept the property being absent as completed too, the same way the response summary counts
+ * legacy events. An explicit `false` stays excluded from sent-event notifications.
*/
export function getSurveyNotificationFilters(
surveyId: string,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 91d26de5051d..f4368eed56bc 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -3803,6 +3803,7 @@ export interface SurveyDisplayConditions {
export enum SurveyEventName {
SHOWN = 'survey shown',
DISMISSED = 'survey dismissed',
+ ABANDONED = 'survey abandoned',
SENT = 'survey sent',
}
diff --git a/products/surveys/backend/api/test/__snapshots__/test_survey.ambr b/products/surveys/backend/api/test/__snapshots__/test_survey.ambr
index 6ee12cdd79fb..7c1b73b64ecd 100644
--- a/products/surveys/backend/api/test/__snapshots__/test_survey.ambr
+++ b/products/surveys/backend/api/test/__snapshots__/test_survey.ambr
@@ -5,11 +5,11 @@
SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,
count() AS `count()`
FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-01-21 14:40:09.000000', 6, 'UTC')), globalIn(events.uuid,
- (SELECT argMax(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS `argMax(uuid, toTimeZone(timestamp, 'UTC'))`
- FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-01-21 14:40:09.000000', 6, 'UTC')))
- GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))
+ WHERE and(equals(events.team_id, 99999), or(equals(events.event, 'survey sent'), and(in(events.event, tuple('survey dismissed', 'survey abandoned')), equals(coalesce(JSONExtractString(events.properties, '$survey_partially_completed'), ''), 'true'))), greaterOrEquals(events.timestamp, toDateTime64('2024-01-21 14:40:09.000000', 6, 'UTC')), globalIn(events.uuid,
+ (SELECT argMax(events.uuid, tuple(toTimeZone(events.timestamp, 'UTC'), events.uuid)) AS `argMax(uuid, tuple(toTimeZone(timestamp, 'UTC'), uuid))`
+ FROM events
+ WHERE and(equals(events.team_id, 99999), or(equals(events.event, 'survey sent'), and(in(events.event, tuple('survey dismissed', 'survey abandoned')), equals(coalesce(JSONExtractString(events.properties, '$survey_partially_completed'), ''), 'true'))), greaterOrEquals(events.timestamp, toDateTime64('2024-01-21 14:40:09.000000', 6, 'UTC')))
+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))
GROUP BY survey_id
LIMIT 50000 SETTINGS readonly=2,
max_execution_time=60,
@@ -31,11 +31,11 @@
SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,
count() AS `count()`
FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-04-25 14:40:09.000000', 6, 'UTC')), globalIn(events.uuid,
- (SELECT argMax(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS `argMax(uuid, toTimeZone(timestamp, 'UTC'))`
- FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-04-25 14:40:09.000000', 6, 'UTC')))
- GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))
+ WHERE and(equals(events.team_id, 99999), or(equals(events.event, 'survey sent'), and(in(events.event, tuple('survey dismissed', 'survey abandoned')), equals(coalesce(JSONExtractString(events.properties, '$survey_partially_completed'), ''), 'true'))), greaterOrEquals(events.timestamp, toDateTime64('2024-04-25 14:40:09.000000', 6, 'UTC')), globalIn(events.uuid,
+ (SELECT argMax(events.uuid, tuple(toTimeZone(events.timestamp, 'UTC'), events.uuid)) AS `argMax(uuid, tuple(toTimeZone(timestamp, 'UTC'), uuid))`
+ FROM events
+ WHERE and(equals(events.team_id, 99999), or(equals(events.event, 'survey sent'), and(in(events.event, tuple('survey dismissed', 'survey abandoned')), equals(coalesce(JSONExtractString(events.properties, '$survey_partially_completed'), ''), 'true'))), greaterOrEquals(events.timestamp, toDateTime64('2024-04-25 14:40:09.000000', 6, 'UTC')))
+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))
GROUP BY survey_id
LIMIT 50000 SETTINGS readonly=2,
max_execution_time=60,
@@ -57,11 +57,11 @@
SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', '') AS survey_id,
count() AS `count()`
FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-06-10 11:00:00.000000', 6, 'UTC')), globalIn(events.uuid,
- (SELECT argMax(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS `argMax(uuid, toTimeZone(timestamp, 'UTC'))`
- FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.event, 'survey sent'), greaterOrEquals(events.timestamp, toDateTime64('2024-06-10 11:00:00.000000', 6, 'UTC')))
- GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))
+ WHERE and(equals(events.team_id, 99999), or(equals(events.event, 'survey sent'), and(in(events.event, tuple('survey dismissed', 'survey abandoned')), equals(coalesce(JSONExtractString(events.properties, '$survey_partially_completed'), ''), 'true'))), greaterOrEquals(events.timestamp, toDateTime64('2024-06-10 11:00:00.000000', 6, 'UTC')), globalIn(events.uuid,
+ (SELECT argMax(events.uuid, tuple(toTimeZone(events.timestamp, 'UTC'), events.uuid)) AS `argMax(uuid, tuple(toTimeZone(timestamp, 'UTC'), uuid))`
+ FROM events
+ WHERE and(equals(events.team_id, 99999), or(equals(events.event, 'survey sent'), and(in(events.event, tuple('survey dismissed', 'survey abandoned')), equals(coalesce(JSONExtractString(events.properties, '$survey_partially_completed'), ''), 'true'))), greaterOrEquals(events.timestamp, toDateTime64('2024-06-10 11:00:00.000000', 6, 'UTC')))
+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_id'), ''), 'null'), '^"|"$', ''), if(ifNull(equals(coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', ''), ''), ''), 0), toString(events.uuid), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$survey_submission_id'), ''), 'null'), '^"|"$', '')))))
GROUP BY survey_id
LIMIT 50000 SETTINGS readonly=2,
max_execution_time=60,
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 9ddf56fd78cf..8d206df06d63 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -5648,6 +5648,40 @@ class TestResponsesCount(ClickhouseTestMixin, APIBaseTest):
class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):
+ @parameterized.expand([("survey dismissed",), ("survey abandoned",)])
+ def test_partially_completed_closures_count_as_responses(self, event_name: str) -> None:
+ survey = Survey.objects.create(
+ team=self.team,
+ name="Partial responses",
+ questions=[{"type": "open", "question": "What could we improve?"}],
+ start_date=datetime(2024, 6, 1, tzinfo=UTC),
+ )
+ create_person(team=self.team, distinct_ids=["respondent"])
+ for index, partially_completed in enumerate([True, False]):
+ _create_event(
+ team=self.team,
+ event=event_name,
+ distinct_id="respondent",
+ timestamp=f"2024-06-10 10:0{index}:00",
+ properties={
+ "$survey_id": str(survey.id),
+ "$survey_submission_id": f"submission-{index}",
+ "$survey_partially_completed": partially_completed,
+ **({"$survey_response": "More examples"} if partially_completed else {}),
+ },
+ )
+ flush_persons_and_events()
+
+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/{survey.id}/stats/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["stats"]["survey sent"]["total_count"], 1)
+ self.assertEqual(
+ response.json()["stats"]["survey dismissed"]["total_count"], int(event_name == "survey dismissed")
+ )
+ counts = self.client.get(f"/api/projects/{self.team.id}/surveys/responses_count")
+ self.assertEqual(counts.status_code, status.HTTP_200_OK)
+ self.assertEqual(counts.json(), {str(survey.id): 1})
+
def test_survey_stats_nonexistent_survey(self):
response = self.client.get(f"/api/projects/{self.team.id}/surveys/12345/stats/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
@@ -7176,9 +7210,8 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(data["results"]), 1)
self.assertEqual(data["results"][0]["distinct_id"], "new")
- def test_merges_answers_split_across_submission_events(self):
- """A submission split across events — rating on one, free text on another, neither
- repeating the other's answer — should surface as one row carrying both answers."""
+ @parameterized.expand([("survey sent",), ("survey dismissed",), ("survey abandoned",)])
+ def test_merges_answers_split_across_submission_events(self, last_event: str):
create_person(team=self.team, distinct_ids=["split"])
submission_id = str(uuid.uuid4())
# Event 1 (not completed): rating only.
@@ -7194,17 +7227,18 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):
"$survey_completed": "false",
},
)
- # Event 2 (completed): free text only — the rating is NOT repeated here.
+ # Event 2: free text only — the rating is NOT repeated here.
_create_event(
team=self.team,
- event="survey sent",
+ event=last_event,
distinct_id="split",
timestamp="2024-06-10 09:05:30",
properties={
"$survey_id": str(self.survey.id),
"$survey_submission_id": submission_id,
f"$survey_response_{self.question_id_text}": "Because reasons",
- "$survey_completed": "true",
+ "$survey_completed": last_event == "survey sent",
+ "$survey_partially_completed": last_event != "survey sent",
},
)
flush_persons_and_events()
@@ -7732,9 +7766,8 @@ class TestSurveyStatsPerQuestion(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(per_q[choice_qid]["distribution"], {"yes": 2, "<other>": 1})
self.assertEqual(per_q[choice_qid]["response_count"], 3)
- def test_per_question_stats_merges_answers_across_submission_events(self):
- """Answers split across a submission's events should all count toward per-question stats,
- even when the completed event only carries one of them."""
+ @parameterized.expand([("survey sent",), ("survey dismissed",), ("survey abandoned",)])
+ def test_per_question_stats_merges_answers_across_submission_events(self, last_event: str):
create_person(team=self.team, distinct_ids=["split-user"])
submission_id = str(uuid.uuid4())
# Event 1 (not completed): rating + choice only.
@@ -7754,14 +7787,15 @@ class TestSurveyStatsPerQuestion(ClickhouseTestMixin, APIBaseTest):
# Event 2 (completed): open text only — rating/choice are NOT repeated here.
_create_event(
team=self.team,
- event="survey sent",
+ event=last_event,
distinct_id="split-user",
timestamp="2024-06-10 09:01:00",
properties={
"$survey_id": str(self.survey.id),
"$survey_submission_id": submission_id,
f"$survey_response_{self.open_qid}": "Nice",
- "$survey_completed": "true",
+ "$survey_completed": last_event == "survey sent",
+ "$survey_partially_completed": last_event != "survey sent",
},
)
flush_persons_and_events()
diff --git a/products/surveys/backend/responses/fetch_rows.py b/products/surveys/backend/responses/fetch_rows.py
index 2318f9fc49e0..fa04b3e725e8 100644
--- a/products/surveys/backend/responses/fetch_rows.py
+++ b/products/surveys/backend/responses/fetch_rows.py
@@ -122,6 +122,12 @@ SUBMISSION_GROUPING_KEY = (
)
+RESPONSE_EVENT_FILTER = """(event = 'survey sent' OR (
+ event IN ('survey dismissed', 'survey abandoned')
+ AND coalesce(JSONExtractString(properties, '$survey_partially_completed'), '') = 'true'
+))"""
+
+
# Metadata columns appended to every row — known $-prefixed event properties resolved via
# HogQL property accessors (backticked because the keys are literal property names, not
# placeholder values).
@@ -220,7 +226,7 @@ def fetch_response_rows(
)
inner_conditions = [
- "event = 'survey sent'",
+ RESPONSE_EVENT_FILTER,
"properties.`$survey_id` = {survey_id}",
"timestamp >= {start_date}",
"timestamp <= {end_date}",
diff --git a/products/surveys/backend/responses/per_question_stats.py b/products/surveys/backend/responses/per_question_stats.py
index 21489128d6b7..e3b915aa43b7 100644
--- a/products/surveys/backend/responses/per_question_stats.py
+++ b/products/surveys/backend/responses/per_question_stats.py
@@ -11,7 +11,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.models import Team
from products.surveys.backend.models import Survey
-from products.surveys.backend.responses.fetch_rows import SUBMISSION_GROUPING_KEY, resolve_question_metadata
+from products.surveys.backend.responses.fetch_rows import (
+ RESPONSE_EVENT_FILTER,
+ SUBMISSION_GROUPING_KEY,
+ resolve_question_metadata,
+)
@dataclass(frozen=True)
@@ -61,6 +65,7 @@ def fetch_per_question_stats(
"q_idx": ast.Constant(value=question_index),
"q_id": ast.Constant(value=question_id),
"grouping_key": parse_expr(SUBMISSION_GROUPING_KEY),
+ "response_events": parse_expr(RESPONSE_EVENT_FILTER),
}
# For open questions: just count non-empty responses — distribution across free-text
@@ -82,7 +87,7 @@ def fetch_per_question_stats(
timestamp,
{grouping_key} AS submission_key
FROM events
- WHERE event = 'survey sent'
+ WHERE {response_events}
AND properties.`$survey_id` = {survey_id}
AND timestamp >= {start_date}
AND timestamp <= {end_date}
@@ -122,7 +127,7 @@ def fetch_per_question_stats(
timestamp,
{grouping_key} AS submission_key
FROM events
- WHERE event = 'survey sent'
+ WHERE {response_events}
AND properties.`$survey_id` = {survey_id}
AND timestamp >= {start_date}
AND timestamp <= {end_date}
diff --git a/products/surveys/backend/responses/stats.py b/products/surveys/backend/responses/stats.py
index 3aaa118a3a6f..85e9c5bcb175 100644
--- a/products/surveys/backend/responses/stats.py
+++ b/products/surveys/backend/responses/stats.py
@@ -24,7 +24,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.models import Team
from products.surveys.backend.models import Survey
-from products.surveys.backend.responses.fetch_rows import SUBMISSION_GROUPING_KEY
+from products.surveys.backend.responses.fetch_rows import RESPONSE_EVENT_FILTER, SUBMISSION_GROUPING_KEY
from products.surveys.backend.util import SurveyEventName, get_archived_response_uuids
@@ -178,10 +178,10 @@ def calculate_rates(stats: SurveyStats) -> SurveyRates:
return rates
-def _latest_sent_event_uuids_subquery(scan_conditions: str) -> str:
- """HogQL subquery selecting the uuid of the latest "survey sent" event per submission.
+def _latest_response_event_uuids_subquery(scan_conditions: str) -> str:
+ """Select the latest response event UUID per submission.
- Multiple partial "survey sent" events can exist per submission; only the latest per
+ Several sent, dismissed, or abandoned events can exist per submission; only the latest per
$survey_submission_id counts, and events without one count by their own uuid (see
SUBMISSION_GROUPING_KEY). Grouping per $survey_id keeps a submission id scoped to its
survey. `scan_conditions` must start with " AND " and only narrows the scan window; it
@@ -189,9 +189,9 @@ def _latest_sent_event_uuids_subquery(scan_conditions: str) -> str:
against every sent event in the window.
"""
return f"""(
- SELECT argMax(uuid, timestamp)
+ SELECT argMax(uuid, tuple(timestamp, uuid))
FROM events
- WHERE event = '{SurveyEventName.SENT}'{scan_conditions}
+ WHERE {RESPONSE_EVENT_FILTER}{scan_conditions}
GROUP BY properties.$survey_id, {SUBMISSION_GROUPING_KEY}
)"""
@@ -274,27 +274,26 @@ def get_survey_stats(
conditions.append("properties.$survey_id IN {survey_ids}")
placeholders["survey_ids"] = ast.Constant(value=[str(id) for id in active_survey_ids])
- # Partially-completed submissions carry a synthetic "survey dismissed" event; don't count those.
- conditions.append("(event != {dismissed} OR coalesce(properties.$survey_partially_completed, '') != 'true')")
-
condition_sql = "".join(f"\n AND {condition}" for condition in conditions)
- sent_dedup_sql = f"(event != {{sent}} OR uuid IN {_latest_sent_event_uuids_subquery(date_conditions)})"
+ sent_dedup_sql = (
+ f"(NOT {RESPONSE_EVENT_FILTER} OR uuid IN {_latest_response_event_uuids_subquery(date_conditions)})"
+ )
tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)
# Query 1: Base Stats
base_stats_query = f"""
SELECT
- event AS event_name,
+ if({RESPONSE_EVENT_FILTER}, {{sent}}, event) AS event_name,
count() AS total_count,
count(DISTINCT person_id) AS unique_persons,
if(count() > 0, min(timestamp), NULL) AS first_seen,
if(count() > 0, max(timestamp), NULL) AS last_seen
FROM events
- WHERE event IN ({{shown}}, {{dismissed}}, {{sent}}){condition_sql}
+ WHERE (event IN ({{shown}}, {{dismissed}}, {{sent}}) OR {RESPONSE_EVENT_FILTER}){condition_sql}
AND {sent_dedup_sql}
- GROUP BY event
+ GROUP BY event_name
"""
results_base = execute_hogql_query(
base_stats_query,
@@ -310,10 +309,10 @@ def get_survey_stats(
FROM (
SELECT person_id
FROM events
- WHERE event IN ({{dismissed}}, {{sent}}){condition_sql}
+ WHERE (event = {{dismissed}} OR {RESPONSE_EVENT_FILTER}){condition_sql}
GROUP BY person_id
- HAVING countIf(event = {{dismissed}}) > 0
- AND countIf(event = {{sent}}) > 0
+ HAVING countIf(event = {{dismissed}} AND NOT {RESPONSE_EVENT_FILTER}) > 0
+ AND countIf({RESPONSE_EVENT_FILTER}) > 0
)
"""
dismissed_and_sent_count_result = execute_hogql_query(
@@ -370,7 +369,7 @@ def get_survey_stats(
def get_survey_responses_count(
*, team: Team, exclude_archived: bool = False, survey_ids: list[str] | None = None
) -> dict[str, int]:
- """Count unique "survey sent" responses per survey, keyed by survey id.
+ """Count captured submissions per survey, including incomplete responses.
Only events since the earliest survey start date in the project are scanned. With no
started survey there can be no responses, so that case returns empty without a query.
@@ -382,7 +381,7 @@ def get_survey_responses_count(
return {}
placeholders: dict[str, ast.Expr] = {"since": ast.Constant(value=earliest_start_date)}
- conditions = [f"uuid IN {_latest_sent_event_uuids_subquery(' AND timestamp >= {since}')}"]
+ conditions = [f"uuid IN {_latest_response_event_uuids_subquery(' AND timestamp >= {since}')}"]
if exclude_archived:
archived_uuids = get_archived_response_uuids(None, team.pk)
@@ -401,7 +400,7 @@ def get_survey_responses_count(
query = f"""
SELECT properties.$survey_id AS survey_id, count()
FROM events
- WHERE event = '{SurveyEventName.SENT}'
+ WHERE {RESPONSE_EVENT_FILTER}
AND timestamp >= {{since}}{condition_sql}
GROUP BY survey_id
LIMIT {MAX_SELECT_RETURNED_ROWS}
diff --git a/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx b/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx
new file mode 100644
index 000000000000..756993e5f01b
--- /dev/null
+++ b/products/surveys/frontend/components/SurveyResponseBreakdown.stories.tsx
@@ -0,0 +1,27 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { getSurveyResponseOutcomeBreakdown } from 'scenes/surveys/utils'
+
+import { SurveyResponseBreakdown } from './SurveyResponseBreakdown'
+
+const meta: Meta<typeof SurveyResponseBreakdown> = {
+ title: 'Surveys/SurveyResponseBreakdown',
+ component: SurveyResponseBreakdown,
+ args: { outcomes: getSurveyResponseOutcomeBreakdown([2, 1, 2]) },
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const Mixed: Story = {}
+export const Empty: Story = { args: { outcomes: getSurveyResponseOutcomeBreakdown([0, 0, 0]) } }
+export const DismissalOnly: Story = { args: { outcomes: getSurveyResponseOutcomeBreakdown([0, 3, 0]) } }
+export const Narrow: Story = {
+ decorators: [
+ (Story) => (
+ <div className="w-96">
+ <Story />
+ </div>
+ ),
+ ],
+}
diff --git a/products/surveys/frontend/components/SurveyResponseBreakdown.tsx b/products/surveys/frontend/components/SurveyResponseBreakdown.tsx
new file mode 100644
index 000000000000..122e56550323
--- /dev/null
+++ b/products/surveys/frontend/components/SurveyResponseBreakdown.tsx
@@ -0,0 +1,24 @@
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import type { SurveyResponseOutcome } from 'scenes/surveys/utils'
+
+export function SurveyResponseBreakdown({ outcomes }: { outcomes: SurveyResponseOutcome[] }): JSX.Element {
+ return (
+ <Tooltip title="Percentages are of all responses matching the current filters. Each submission counts once. Dismissed and abandoned responses contain partial answers.">
+ <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-xs">
+ <span className="text-secondary">Of responses:</span>
+ {outcomes.map((outcome) => (
+ <span key={outcome.label} className="inline-flex items-center gap-1 whitespace-nowrap">
+ <LemonTag type={outcome.label === 'Completed' ? 'success' : 'warning'}>
+ {outcome.label}
+ </LemonTag>
+ <span className="tabular-nums">
+ {humanFriendlyNumber(outcome.count)} ({percentage(outcome.percentage, 1)})
+ </span>
+ </span>
+ ))}
+ </div>
+ </Tooltip>
+ )
+}
diff --git a/products/surveys/skills/debugging-surveys/SKILL.md b/products/surveys/skills/debugging-surveys/SKILL.md
index d2cf0b584195..1d302e5435c5 100644
--- a/products/surveys/skills/debugging-surveys/SKILL.md
+++ b/products/surveys/skills/debugging-surveys/SKILL.md
@@ -107,13 +107,19 @@ The radio in `frontend/src/scenes/surveys/SurveyResponsesCollection.tsx`. "Any q
least one question is answered…" is `true`; "Complete survey: the response is stored when all
questions are answered" is `false`.
-- `true` → `sendSurveyEvent` fires on **every** `onNextButtonClick`, so one `survey sent` per
+- `true` -> `sendSurveyEvent` fires on **every** `onNextButtonClick`, so one `survey sent` per
question answered, all sharing a `$survey_submission_id` with `$survey_completed` running
- `false … true`. The responses table collapses them by `argMax(uuid, timestamp)` per submission id
- (`buildPartialResponsesFilter`, `frontend/src/scenes/surveys/utils.ts`), so **raw SQL shows far
- more rows than the UI** and the extras look like broken submissions.
-- `false` → one event, at the end of the path. The table instead filters
- `$survey_completed != 'false'`, keeping events where the property is absent (pre-1.240.0 SDKs).
+ `false ... true`.
+- `false` -> one `survey sent` event, at the end of the path.
+
+The setting controls capture, not response visibility. The results include every `survey sent`
+and every `survey dismissed` or `survey abandoned` marked `$survey_partially_completed = true`.
+`buildMergedSubmissionsSubquery` in `frontend/src/scenes/surveys/utils.ts` merges the latest
+answer per question for each submission ID; events without an ID stay separate. **Raw event
+counts can exceed response counts.** A completed event takes precedence over earlier partial
+closures. Otherwise the outcome chip reads "Dismissed" when the latest response event is a
+dismissal, and "Abandoned" for other unfinished submissions. "Abandoned" does not prove a
+page-unload event or inactivity timeout occurred; a later completion updates the same row.
**The defaults disagree by creation path:** `NEW_SURVEY` sets `true`
(`frontend/src/scenes/surveys/constants.tsx`) but the Django model default is `False`