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): filter lists before pagination (#91139)

Lucas Fariaffb10adf7218
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 70f7089b5ed7..c797c7480c0b 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -196,6 +196,7 @@ import {
SlackChannelType,
SubscriptionType,
Survey,
+ SurveyType,
SurveyStatsResponse,
TeamType,
TwilioPhoneNumberType,
@@ -5452,7 +5453,10 @@ const api = {
offset?: number
search?: string
archived?: boolean
+ created_by?: number
ids?: string
+ status?: 'draft' | 'running' | 'complete'
+ type?: SurveyType
} = {
limit: SURVEY_PAGE_SIZE,
}
diff --git a/frontend/src/scenes/surveys/components/SurveysTable.tsx b/frontend/src/scenes/surveys/components/SurveysTable.tsx
index afd8461b4388..4753c03e56b5 100644
--- a/frontend/src/scenes/surveys/components/SurveysTable.tsx
+++ b/frontend/src/scenes/surveys/components/SurveysTable.tsx
@@ -346,9 +346,13 @@ export function SurveysTable(): JSX.Element {
]
)
+ const hasSearchTerm = Boolean(searchTerm.trim())
+ const hasActiveFilters =
+ hasSearchTerm || filters.status !== 'any' || filters.type !== 'any' || filters.created_by != null
const isInitialDataLoad = surveys.length === 0 && hasNextPage
const isTableLoading = dataLoading || isInitialDataLoad
- const shouldShowEmptyState = !isTableLoading && surveys.length === 0
+ const shouldShowEmptyState =
+ !isTableLoading && tab === SurveysTabs.Active && !hasActiveFilters && surveys.length === 0
if (shouldShowEmptyState) {
return <SurveysEmptyState />
@@ -436,10 +440,10 @@ export function SurveysTable(): JSX.Element {
emptyState={tab === SurveysTabs.Active ? 'No surveys. Create a new survey?' : 'No surveys found'}
loading={isTableLoading}
footer={
- (searchTerm ? hasNextSearchPage : hasNextPage) && (
+ (hasSearchTerm ? hasNextSearchPage : hasNextPage) && (
<div className="flex justify-center p-1">
<LemonButton
- onClick={searchTerm ? loadNextSearchPage : loadNextPage}
+ onClick={hasSearchTerm ? loadNextSearchPage : loadNextPage}
className="min-w-full text-center"
disabledReason={isTableLoading ? 'Loading surveys' : ''}
>
diff --git a/frontend/src/scenes/surveys/surveysLogic.test.ts b/frontend/src/scenes/surveys/surveysLogic.test.ts
index e0e9fcf62278..72e3ebc81878 100644
--- a/frontend/src/scenes/surveys/surveysLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveysLogic.test.ts
@@ -1,6 +1,9 @@
+import { waitFor } from '@testing-library/react'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import api, { CountedPaginatedResponse } from 'lib/api'
+
import { useMocks } from '~/mocks/jest'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -32,22 +35,43 @@ const createTestSurvey = (id: string, name: string): Survey => ({
user_access_level: AccessControlLevel.Editor,
})
+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((promiseResolve) => {
+ resolve = promiseResolve
+ })
+ return { promise, resolve }
+}
+
describe('surveysLogic', () => {
describe('search functionality', () => {
let logic: ReturnType<typeof surveysLogic.build>
+ let surveyListRequests: URL[]
+ let responseCountRequests: URL[]
beforeEach(async () => {
initKeaTests()
+ surveyListRequests = []
+ responseCountRequests = []
logic = surveysLogic()
- logic.mount()
useMocks({
get: {
- '/api/projects/:team/surveys/': () => [200, { count: 0, results: [], next: null, previous: null }],
- '/api/projects/:team/surveys/responses_count': () => [200, {}],
+ '/api/projects/:team/surveys/': ({ request }) => {
+ surveyListRequests.push(new URL(request.url))
+ return [200, { count: 0, results: [], next: null, previous: null }]
+ },
+ '/api/projects/:team/surveys/responses_count': ({ request }) => {
+ const url = new URL(request.url)
+ responseCountRequests.push(url)
+ const requestedSurveyIds = url.searchParams.get('survey_ids')?.split(',') ?? []
+
+ return [200, requestedSurveyIds.includes('survey-1') ? { 'survey-1': 12 } : {}]
+ },
},
})
+ logic.mount()
await expectLogic(logic).toFinishAllListeners()
})
@@ -134,6 +158,76 @@ describe('surveysLogic', () => {
hasNextPage: false,
})
})
+
+ it('filters on the server before paginating', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setSurveysFilters({
+ created_by: 42,
+ status: 'running',
+ type: SurveyType.Widget,
+ })
+ }).toFinishAllListeners()
+
+ const params = surveyListRequests.at(-1)?.searchParams
+ expect(params?.get('archived')).toEqual('false')
+ expect(params?.get('created_by')).toEqual('42')
+ expect(params?.get('status')).toEqual('running')
+ expect(params?.get('type')).toEqual(SurveyType.Widget)
+ expect(params?.get('limit')).toEqual('100')
+ })
+
+ it('keeps the latest filtered results when requests finish out of order', async () => {
+ const olderRequest = deferred<CountedPaginatedResponse<Survey>>()
+ const newerRequest = deferred<CountedPaginatedResponse<Survey>>()
+ const olderSurvey = createTestSurvey('older', 'Older filter result')
+ const newerSurvey = createTestSurvey('newer', 'Newer filter result')
+ const listSpy = jest
+ .spyOn(api.surveys, 'list')
+ .mockImplementationOnce(() => olderRequest.promise)
+ .mockImplementationOnce(() => newerRequest.promise)
+
+ logic.actions.setSurveysFilters({ created_by: 41 })
+ logic.actions.setSurveysFilters({ created_by: 42 })
+
+ expect(listSpy).toHaveBeenNthCalledWith(1, expect.objectContaining({ created_by: 41 }))
+ expect(listSpy).toHaveBeenNthCalledWith(2, expect.objectContaining({ created_by: 42 }))
+
+ newerRequest.resolve({ count: 1, results: [newerSurvey] })
+ await waitFor(() => expect(logic.values.data.surveys).toEqual([newerSurvey]))
+
+ olderRequest.resolve({ count: 1, results: [olderSurvey] })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.data.surveys).toEqual([newerSurvey])
+ })
+
+ it('loads response counts for each page and merges them', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/surveys/': ({ request }) => {
+ const offset = new URL(request.url).searchParams.get('offset')
+ const survey =
+ offset === '1'
+ ? createTestSurvey('survey-2', 'Second survey')
+ : createTestSurvey('survey-1', 'First survey')
+
+ return [200, { count: 2, results: [survey], next: null, previous: null }]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSurveys()).toFinishAllListeners()
+
+ expect(responseCountRequests).toHaveLength(1)
+ expect(responseCountRequests[0].searchParams.get('survey_ids')).toEqual('survey-1')
+ expect(logic.values.surveysResponsesCount).toEqual({ 'survey-1': 12 })
+
+ await expectLogic(logic, () => logic.actions.loadNextPage()).toFinishAllListeners()
+
+ expect(responseCountRequests).toHaveLength(2)
+ expect(responseCountRequests[1].searchParams.get('survey_ids')).toEqual('survey-2')
+ expect(logic.values.surveysResponsesCount).toEqual({ 'survey-1': 12, 'survey-2': 0 })
+ })
})
describe('url syncing', () => {
diff --git a/frontend/src/scenes/surveys/surveysLogic.tsx b/frontend/src/scenes/surveys/surveysLogic.tsx
index e3fc64127d44..dbb29b58d1e0 100644
--- a/frontend/src/scenes/surveys/surveysLogic.tsx
+++ b/frontend/src/scenes/surveys/surveysLogic.tsx
@@ -57,7 +57,7 @@ function hasMorePages(surveys: any[], count: number): boolean {
}
export interface SurveysFilters {
- status: string
+ status: 'any' | 'complete' | 'draft' | 'running'
type: SurveyType | 'any'
created_by: null | number
archived: boolean
@@ -75,10 +75,6 @@ function mergeSurveysData(
response: CountedPaginatedResponse<Survey>,
appendResults = false
): SurveyDataState {
- if (response.results.length === 0) {
- return currentData
- }
-
const surveys = appendResults ? [...currentData.surveys, ...response.results] : response.results
return {
@@ -93,10 +89,6 @@ function mergeSearchSurveysData(
response: CountedPaginatedResponse<Survey>,
appendResults = false
): SurveyDataState {
- if (appendResults && response.results.length === 0) {
- return currentData
- }
-
const searchSurveys = appendResults ? [...currentData.searchSurveys, ...response.results] : response.results
return {
@@ -106,6 +98,20 @@ function mergeSearchSurveysData(
}
}
+type SurveyListParams = NonNullable<Parameters<typeof api.surveys.list>[0]>
+
+function getSurveyListParams(filters: Partial<SurveysFilters>, searchTerm?: string, offset?: number): SurveyListParams {
+ return {
+ limit: SURVEY_PAGE_SIZE,
+ offset,
+ search: searchTerm?.trim() || undefined,
+ archived: filters.archived ?? false,
+ created_by: filters.created_by ?? undefined,
+ status: filters.status !== 'any' ? filters.status : undefined,
+ type: filters.type !== 'any' ? filters.type : undefined,
+ }
+}
+
function deleteSurvey(surveys: Survey[], id: string): Survey[] {
return surveys.filter((s) => s.id !== id)
}
@@ -133,7 +139,7 @@ export interface surveysLogicValues {
hasNextSearchPage: boolean
isAppearanceModalOpen: boolean
preferredEditor: 'full' | 'guided'
- searchTerm: any
+ searchTerm: string
searchedSurveys: Survey[]
showSurveysDisabledBanner: boolean
sidePanelContext: SidePanelSceneContext
@@ -275,7 +281,7 @@ export interface surveysLogicActions {
value: true
}
}
- loadResponsesCount: (surveyIds: string) => string
+ loadResponsesCount: (surveyIds: string[]) => string[]
loadResponsesCountFailure: (
error: string,
errorObject?: any
@@ -285,16 +291,26 @@ export interface surveysLogicActions {
}
loadResponsesCountSuccess: (
surveysResponsesCount: {
- [key: string]: number
+ [x: string]: number
},
- payload?: string
+ payload?: string[]
) => {
surveysResponsesCount: {
- [key: string]: number
+ [x: string]: number
}
- payload?: string
- }
- loadSearchResults: () => any
+ payload?: string[]
+ }
+ loadSearchResults: (
+ options:
+ | {
+ debounce?: boolean
+ }
+ | undefined
+ ) =>
+ | {
+ debounce?: boolean
+ }
+ | undefined
loadSearchResultsFailure: (
error: string,
errorObject?: any
@@ -304,10 +320,18 @@ export interface surveysLogicActions {
}
loadSearchResultsSuccess: (
data: SurveyDataState,
- payload?: any
+ payload?:
+ | {
+ debounce?: boolean
+ }
+ | undefined
) => {
data: SurveyDataState
- payload?: any
+ payload?:
+ | {
+ debounce?: boolean
+ }
+ | undefined
}
loadSurveys: () => any
loadSurveysFailure: (
@@ -396,13 +420,13 @@ export interface surveysLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveysLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- searchedSurveys: (data: SurveyDataState, searchTerm: any, filters: Partial<SurveysFilters>) => Survey[]
+ searchedSurveys: (data: SurveyDataState, searchTerm: string) => Survey[]
surveysStylingAvailable: (
- hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
) => boolean
formBuilderEnabled: (enabledFlags: FeatureFlagsSet) => boolean
globalSurveyAppearanceConfigAvailable: (
- hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
) => boolean
showSurveysDisabledBanner: (currentTeam: TeamPublicType | TeamType | null) => boolean
}
@@ -415,6 +439,12 @@ export type surveysLogicType = MakeLogicType<
surveysLogicMeta
>
+function loadResponseCountsForSurveys(loadResponsesCount: (surveyIds: string[]) => void, surveys: Survey[]): void {
+ if (surveys.length > 0) {
+ loadResponsesCount(surveys.map((survey) => survey.id))
+ }
+}
+
export const surveysLogic = kea<surveysLogicType>([
path(['scenes', 'surveys', 'surveysLogic']),
connect(() => ({
@@ -450,7 +480,7 @@ export const surveysLogic = kea<surveysLogicType>([
source: SURVEY_CREATED_SOURCE
) => ({ toolOutput, source }),
}),
- loaders(({ values, actions }) => ({
+ loaders(({ values, actions, cache }) => ({
data: {
__default: {
surveys: [] as Survey[],
@@ -459,39 +489,56 @@ export const surveysLogic = kea<surveysLogicType>([
searchSurveysCount: 0,
} as SurveyDataState,
loadSurveys: async () => {
- const response = await api.surveys.list()
+ const requestId = (cache.surveyListRequestSequence = (cache.surveyListRequestSequence ?? 0) + 1)
+ const response = await api.surveys.list(getSurveyListParams(values.filters))
+ if (requestId !== cache.surveyListRequestSequence) {
+ return values.data
+ }
+ loadResponseCountsForSurveys(actions.loadResponsesCount, response.results)
return mergeSurveysData(values.data, response)
},
loadNextPage: async () => {
+ const requestId = (cache.surveyListRequestSequence = (cache.surveyListRequestSequence ?? 0) + 1)
const offset = values.data.surveys.length
- const response = await api.surveys.list({
- limit: SURVEY_PAGE_SIZE,
- offset,
- })
+ const response = await api.surveys.list(getSurveyListParams(values.filters, undefined, offset))
+ if (requestId !== cache.surveyListRequestSequence) {
+ return values.data
+ }
+ loadResponseCountsForSurveys(actions.loadResponsesCount, response.results)
return mergeSurveysData(values.data, response, true)
},
- loadSearchResults: async () => {
+ loadSearchResults: async (options: { debounce?: boolean } | undefined, breakpoint) => {
+ const requestId = (cache.surveyListRequestSequence = (cache.surveyListRequestSequence ?? 0) + 1)
+ if (options?.debounce) {
+ await breakpoint(300)
+ }
+ if (requestId !== cache.surveyListRequestSequence) {
+ return values.data
+ }
const trimmedSearchTerm = values.searchTerm?.trim() || ''
if (trimmedSearchTerm === '') {
return mergeSearchSurveysData(values.data, { results: [], count: 0 })
}
- const response = await api.surveys.list({
- limit: SURVEY_PAGE_SIZE,
- search: trimmedSearchTerm,
- })
+ const response = await api.surveys.list(getSurveyListParams(values.filters, trimmedSearchTerm))
+ breakpoint()
+ if (requestId !== cache.surveyListRequestSequence) {
+ return values.data
+ }
+ loadResponseCountsForSurveys(actions.loadResponsesCount, response.results)
return mergeSearchSurveysData(values.data, response)
},
loadNextSearchPage: async () => {
+ const requestId = (cache.surveyListRequestSequence = (cache.surveyListRequestSequence ?? 0) + 1)
const offset = values.data.searchSurveys.length
- const response = await api.surveys.list({
- search: values.searchTerm,
- limit: SURVEY_PAGE_SIZE,
- offset,
- })
+ const response = await api.surveys.list(getSurveyListParams(values.filters, values.searchTerm, offset))
+ if (requestId !== cache.surveyListRequestSequence) {
+ return values.data
+ }
+ loadResponseCountsForSurveys(actions.loadResponsesCount, response.results)
return mergeSearchSurveysData(values.data, response, true)
},
deleteSurvey: async (id) => {
@@ -530,9 +577,11 @@ export const surveysLogic = kea<surveysLogicType>([
},
surveysResponsesCount: {
__default: {} as { [key: string]: number },
- loadResponsesCount: async (surveyIds: string) => {
- const surveysResponsesCount = await api.surveys.getResponsesCount(surveyIds)
- return surveysResponsesCount
+ loadResponsesCount: async (surveyIds: string[]) => {
+ const responseCounts = await api.surveys.getResponsesCount(surveyIds.join(','))
+ const countsForRequestedSurveys = Object.fromEntries(surveyIds.map((surveyId) => [surveyId, 0]))
+
+ return { ...values.surveysResponsesCount, ...countsForRequestedSurveys, ...responseCounts }
},
},
duplicatedSurvey: {
@@ -597,9 +646,12 @@ export const surveysLogic = kea<surveysLogicType>([
setTab: (_, { tab }) => tab,
},
],
- searchTerm: {
- setSearchTerm: (_, { searchTerm }) => searchTerm,
- },
+ searchTerm: [
+ '',
+ {
+ setSearchTerm: (_, { searchTerm }) => searchTerm,
+ },
+ ],
filters: [
{
archived: false,
@@ -667,15 +719,14 @@ export const surveysLogic = kea<surveysLogicType>([
actions.loadSurveys()
},
setSurveysFilters: () => {
- actions.loadSurveys()
+ if (values.searchTerm.trim()) {
+ actions.loadSearchResults(undefined)
+ } else {
+ actions.loadSurveys()
+ }
},
loadSurveysSuccess: () => {
actions.loadCurrentTeam()
-
- if (values.data.surveys.length > 0) {
- const surveyIds = values.data.surveys.map((s) => s.id).join(',')
- actions.loadResponsesCount(surveyIds)
- }
},
loadResponsesCountSuccess: () => {
if (Object.values(values.surveysResponsesCount).some((count) => count > 0)) {
@@ -708,36 +759,18 @@ export const surveysLogic = kea<surveysLogicType>([
router.actions.push(urls.survey(toolOutput.survey_id) + '?edit=true')
}
},
- setSearchTerm: async (_, breakpoint) => {
- await breakpoint(300)
- actions.loadSearchResults()
+ setSearchTerm: () => {
+ if (values.searchTerm.trim()) {
+ actions.loadSearchResults({ debounce: true })
+ } else {
+ actions.loadSurveys()
+ }
},
})),
selectors({
searchedSurveys: [
- (selectors) => [selectors.data, selectors.searchTerm, selectors.filters],
- (data: SurveyDataState, searchTerm, filters: Partial<SurveysFilters>) => {
- let searchedSurveys = searchTerm?.trim() ? data.searchSurveys : data.surveys
-
- const { status, type, created_by, archived } = filters
- if (status !== 'any') {
- searchedSurveys = searchedSurveys.filter((survey: Survey) => getSurveyStatus(survey) === status)
- }
- if (type !== 'any') {
- searchedSurveys = searchedSurveys.filter((survey: Survey) => survey.type === type)
- }
- if (created_by) {
- searchedSurveys = searchedSurveys.filter((survey: Survey) => survey.created_by?.id === created_by)
- }
-
- if (archived) {
- searchedSurveys = searchedSurveys.filter((survey: Survey) => survey.archived)
- } else {
- searchedSurveys = searchedSurveys.filter((survey: Survey) => !survey.archived)
- }
-
- return searchedSurveys
- },
+ (selectors) => [selectors.data, selectors.searchTerm],
+ (data: SurveyDataState, searchTerm: string) => (searchTerm.trim() ? data.searchSurveys : data.surveys),
],
breadcrumbs: [
() => [],
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index 0e0ac033d970..f01a3fe85355 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -2089,6 +2089,24 @@ class SurveyFilterSet(FilterSet):
field_name="id",
label="Filter to a comma-separated list of survey IDs. IDs that don't exist are silently omitted rather than erroring.",
)
+ created_by = django_filters.NumberFilter(
+ field_name="created_by_id",
+ label="Filter surveys by the ID of the user who created them.",
+ )
+ status = django_filters.ChoiceFilter(
+ choices=[("draft", "Draft"), ("running", "Running"), ("complete", "Complete")],
+ method="filter_status",
+ label="Filter surveys by their current status.",
+ )
+
+ def filter_status(self, queryset: QuerySet, _name: str, value: str) -> QuerySet:
+ if value == "draft":
+ return queryset.filter(start_date__isnull=True)
+ if value == "running":
+ return queryset.filter(start_date__isnull=False, end_date__isnull=True)
+ if value == "complete":
+ return queryset.filter(end_date__isnull=False)
+ return queryset
class Meta:
model = Survey
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index c1a3bb1ebc3a..a06d09820c9c 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -25,6 +25,7 @@ from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest
from posthog.constants import AvailableFeature
from posthog.models import Team
from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.user import User
from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
@@ -7270,6 +7271,64 @@ class TestSurveyListTypeFilter(APIBaseTest):
self.assertEqual(len(data["results"]), 1)
self.assertEqual(data["results"][0]["name"], "widget survey")
+ def test_filter_by_creator_before_paginating(self):
+ own_survey = Survey.objects.create(
+ team=self.team,
+ name="my survey",
+ type="popover",
+ questions=[],
+ created_by=self.user,
+ )
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ Survey.objects.create(
+ team=self.team,
+ name="someone else's survey",
+ type="popover",
+ questions=[],
+ created_by=other_user,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/?created_by={self.user.id}&limit=1")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["count"], 1)
+ self.assertIsNone(data["next"])
+ self.assertEqual([survey["id"] for survey in data["results"]], [str(own_survey.id)])
+
+ @parameterized.expand(
+ [
+ ("draft", "draft survey"),
+ ("running", "running survey"),
+ ("complete", "complete survey"),
+ ]
+ )
+ def test_filter_by_status(self, survey_status: str, expected_name: str):
+ now = datetime.now(UTC)
+ Survey.objects.create(team=self.team, name="draft survey", type="popover", questions=[])
+ Survey.objects.create(
+ team=self.team,
+ name="running survey",
+ type="popover",
+ questions=[],
+ start_date=now,
+ )
+ Survey.objects.create(
+ team=self.team,
+ name="complete survey",
+ type="popover",
+ questions=[],
+ start_date=now - timedelta(days=1),
+ end_date=now,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/?status={survey_status}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["count"], 1)
+ self.assertEqual(data["results"][0]["name"], expected_name)
+
def test_filter_by_ids(self):
first = Survey.objects.create(team=self.team, name="first", type="popover", questions=[])
second = Survey.objects.create(team=self.team, name="second", type="popover", questions=[])
diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.ts
index 705353386435..67e1b38a5c13 100644
--- a/products/surveys/frontend/generated/api.schemas.ts
+++ b/products/surveys/frontend/generated/api.schemas.ts
@@ -2155,6 +2155,10 @@ export interface SurveyGlobalStatsResponseApi {
export type SurveysListParams = {
archived?: boolean
+ /**
+ * Filter surveys by the ID of the user who created them.
+ */
+ created_by?: number
/**
* Multiple values may be separated by commas.
*/
@@ -2171,6 +2175,14 @@ export type SurveysListParams = {
* Match against survey `name` and `description`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`.
*/
search?: string
+ /**
+ * Filter surveys by their current status.
+ *
+ * * `draft` - Draft
+ * * `running` - Running
+ * * `complete` - Complete
+ */
+ status?: SurveysListStatus
/**
* * `popover` - popover
* * `widget` - widget
@@ -2180,6 +2192,14 @@ export type SurveysListParams = {
type?: SurveysListType
}
+export type SurveysListStatus = (typeof SurveysListStatus)[keyof typeof SurveysListStatus]
+
+export const SurveysListStatus = {
+ Complete: 'complete',
+ Draft: 'draft',
+ Running: 'running',
+} as const
+
export type SurveysListType = (typeof SurveysListType)[keyof typeof SurveysListType]
export const SurveysListType = {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1f17ddb43d7c..3e77eba222fe 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -97554,6 +97554,10 @@ export namespace Schemas {
export type SurveysListParams = {
archived?: boolean;
+ /**
+ * Filter surveys by the ID of the user who created them.
+ */
+ created_by?: number;
/**
* Multiple values may be separated by commas.
*/
@@ -97570,6 +97574,14 @@ export namespace Schemas {
* Match against survey `name` and `description`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`.
*/
search?: string;
+ /**
+ * Filter surveys by their current status.
+ *
+ * * `draft` - Draft
+ * * `running` - Running
+ * * `complete` - Complete
+ */
+ status?: SurveysListStatus;
/**
* * `popover` - popover
* * `widget` - widget
@@ -97579,6 +97591,15 @@ export namespace Schemas {
type?: SurveysListType;
};
+ export type SurveysListStatus = typeof SurveysListStatus[keyof typeof SurveysListStatus];
+
+
+ export const SurveysListStatus = {
+ Complete: 'complete',
+ Draft: 'draft',
+ Running: 'running',
+ } as const;
+
export type SurveysListType = typeof SurveysListType[keyof typeof SurveysListType];
diff --git a/services/mcp/src/generated/surveys/api.ts b/services/mcp/src/generated/surveys/api.ts
index b41d7e169776..9123ab3a7768 100644
--- a/services/mcp/src/generated/surveys/api.ts
+++ b/services/mcp/src/generated/surveys/api.ts
@@ -18,6 +18,7 @@ export const SurveysListParams = /* @__PURE__ */ zod.object({
export const SurveysListQueryParams = /* @__PURE__ */ zod.object({
archived: zod.boolean().optional(),
+ created_by: zod.number().optional().describe('Filter surveys by the ID of the user who created them.'),
ids: zod.array(zod.string()).optional().describe('Multiple values may be separated by commas.'),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
@@ -27,6 +28,12 @@ export const SurveysListQueryParams = /* @__PURE__ */ zod.object({
.describe(
"Match against survey `name` and `description`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`."
),
+ status: zod
+ .enum(['complete', 'draft', 'running'])
+ .optional()
+ .describe(
+ 'Filter surveys by their current status.\n\n\* `draft` - Draft\n\* `running` - Running\n\* `complete` - Complete'
+ ),
type: zod
.enum(['api', 'external_survey', 'popover', 'widget'])
.optional()
diff --git a/services/mcp/src/tools/generated/surveys.ts b/services/mcp/src/tools/generated/surveys.ts
index 5ff7a6d68591..ce515a889c0c 100644
--- a/services/mcp/src/tools/generated/surveys.ts
+++ b/services/mcp/src/tools/generated/surveys.ts
@@ -359,10 +359,12 @@ const surveysGetAll = (): ToolBase<typeof SurveysGetAllSchema, WithPostHogUrl<Sc
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/`,
query: {
archived: params.archived,
+ created_by: params.created_by,
ids: Array.isArray(params.ids) ? params.ids.join(',') || undefined : params.ids,
limit: params.limit,
offset: params.offset,
search: params.search,
+ status: params.status,
type: params.type,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json
index ec5dced0cc66..41e275da495e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/surveys-get-all.json
@@ -4,6 +4,10 @@
"archived": {
"type": "boolean"
},
+ "created_by": {
+ "description": "Filter surveys by the ID of the user who created them.",
+ "type": "number"
+ },
"ids": {
"description": "Multiple values may be separated by commas.",
"items": {
@@ -23,6 +27,11 @@
"description": "Match against survey `name` and `description`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`.",
"type": "string"
},
+ "status": {
+ "description": "Filter surveys by their current status.\n\n* `draft` - Draft\n* `running` - Running\n* `complete` - Complete",
+ "enum": ["complete", "draft", "running"],
+ "type": "string"
+ },
"type": {
"description": "* `popover` - popover\n* `widget` - widget\n* `external_survey` - external survey\n* `api` - api",
"enum": ["api", "external_survey", "popover", "widget"],