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.

28.7 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'

import { lemonToast } from '@posthog/lemon-ui'

import api, { CountedPaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS, SURVEY_PAGE_SIZE } from 'lib/constants'
import { featureFlagLogic as enabledFlagLogic } from 'lib/logic/featureFlagLogic'
import { pluralize } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { duplicateExistingSurvey, sanitizeSurvey } from 'scenes/surveys/utils'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { deleteFromTree } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { ActivityScope, AvailableFeature, Breadcrumb, ProgressStatus, Survey, SurveyType } from '~/types'

import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { ProductIntentProperties } from '../../lib/utils/product-intents'
import type { TeamPublicType, TeamType } from '../../types'
import { SURVEY_CREATED_SOURCE } from './constants'
import { surveysSdkLogic } from './surveysSdkLogic'
import type { TeamSdkVersions } from './surveyVersionRequirements'
import { captureMaxAISurveyCreationException } from './utils'

export enum SurveysTabs {
    Active = 'active',
    Yours = 'yours',
    Archived = 'archived',
    Notifications = 'notifications',
    History = 'history',
    Settings = 'settings',
}

export function isSurveyDraft(survey: Pick<Survey, 'start_date'>): boolean {
    return !survey.start_date
}

export function getSurveyStatus(survey: Pick<Survey, 'start_date' | 'end_date'>): ProgressStatus {
    if (isSurveyDraft(survey)) {
        return ProgressStatus.Draft
    } else if (!survey.end_date) {
        return ProgressStatus.Running
    }
    return ProgressStatus.Complete
}

function hasMorePages(surveys: any[], count: number): boolean {
    return surveys.length < count
}

export interface SurveysFilters {
    status: 'any' | 'complete' | 'draft' | 'running'
    type: SurveyType | 'any'
    created_by: null | number
    archived: boolean
}

export interface SurveyDataState {
    surveys: Survey[]
    surveysCount: number
    searchSurveys: Survey[]
    searchSurveysCount: number
}

function mergeSurveysData(
    currentData: SurveyDataState,
    response: CountedPaginatedResponse<Survey>,
    appendResults = false
): SurveyDataState {
    const surveys = appendResults ? [...currentData.surveys, ...response.results] : response.results

    return {
        ...currentData,
        surveys,
        surveysCount: response.count ?? currentData.surveysCount,
    }
}

function mergeSearchSurveysData(
    currentData: SurveyDataState,
    response: CountedPaginatedResponse<Survey>,
    appendResults = false
): SurveyDataState {
    const searchSurveys = appendResults ? [...currentData.searchSurveys, ...response.results] : response.results

    return {
        ...currentData,
        searchSurveys,
        searchSurveysCount: response.count ?? 0,
    }
}

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)
}

function updateSurvey(surveys: Survey[], id: string, updatedSurvey: Survey): Survey[] {
    return surveys.map((s) => (s.id === id ? updatedSurvey : s))
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveysLogicValues {
    enabledFlags: FeatureFlagsSet // enabledFlagLogic
    teamSdkVersions: TeamSdkVersions // surveysSdkLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    currentTeamLoading: boolean // teamLogic
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    breadcrumbs: Breadcrumb[]
    data: SurveyDataState
    dataLoading: boolean
    duplicatedSurvey: Survey | null
    duplicatedSurveyLoading: boolean
    filters: Partial<SurveysFilters>
    formBuilderEnabled: boolean
    globalSurveyAppearanceConfigAvailable: boolean
    hasNextPage: boolean
    hasNextSearchPage: boolean
    isAppearanceModalOpen: boolean
    preferredEditor: 'full' | 'guided'
    searchTerm: string
    searchedSurveys: Survey[]
    showSurveysDisabledBanner: boolean
    sidePanelContext: SidePanelSceneContext
    surveyToDuplicate: Survey | null
    surveysResponsesCount: {
        [key: string]: number
    }
    surveysResponsesCountLoading: boolean
    surveysStylingAvailable: boolean
    tab: SurveysTabs
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveysLogicActions {
    addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
    loadCurrentTeam: () => any // teamLogic
    deleteSurvey: (id: any) => any
    deleteSurveyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteSurveySuccess: (
        data: {
            searchSurveys: Survey[]
            searchSurveysCount: number
            surveys: Survey[]
            surveysCount: number
        },
        payload?: any
    ) => {
        data: {
            searchSurveys: Survey[]
            searchSurveysCount: number
            surveys: Survey[]
            surveysCount: number
        }
        payload?: any
    }
    duplicateSurvey: (survey: Survey) => Survey
    duplicateSurveyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    duplicateSurveySuccess: (
        duplicatedSurvey: Survey,
        payload?: Survey
    ) => {
        duplicatedSurvey: Survey
        payload?: Survey
    }
    duplicateToProjects: ({ survey, targetTeamIds }: { survey: Survey; targetTeamIds: number[] }) => {
        survey: Survey
        targetTeamIds: number[]
    }
    duplicateToProjectsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    duplicateToProjectsSuccess: (
        duplicatedSurvey: Survey,
        payload?: {
            survey: Survey
            targetTeamIds: number[]
        }
    ) => {
        duplicatedSurvey: Survey
        payload?: {
            survey: Survey
            targetTeamIds: number[]
        }
    }
    handleMaxSurveyCreated: (
        toolOutput: {
            error?: string
            error_message?: string
            survey_id?: string
            survey_name?: string
            survey_type?: string
        },
        source: SURVEY_CREATED_SOURCE
    ) => {
        source: SURVEY_CREATED_SOURCE
        toolOutput: {
            error?: string | undefined
            error_message?: string | undefined
            survey_id?: string | undefined
            survey_name?: string | undefined
            survey_type?: string | undefined
        }
    }
    loadNextPage: () => {
        value: true
    }
    loadNextPageFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNextPageSuccess: (
        data: SurveyDataState,
        payload?: {
            value: true
        }
    ) => {
        data: SurveyDataState
        payload?: {
            value: true
        }
    }
    loadNextSearchPage: () => {
        value: true
    }
    loadNextSearchPageFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNextSearchPageSuccess: (
        data: SurveyDataState,
        payload?: {
            value: true
        }
    ) => {
        data: SurveyDataState
        payload?: {
            value: true
        }
    }
    loadResponsesCount: (surveyIds: string[]) => string[]
    loadResponsesCountFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadResponsesCountSuccess: (
        surveysResponsesCount: {
            [x: string]: number
        },
        payload?: string[]
    ) => {
        surveysResponsesCount: {
            [x: string]: number
        }
        payload?: string[]
    }
    loadSearchResults: (
        options:
            | {
                  debounce?: boolean
              }
            | undefined
    ) =>
        | {
              debounce?: boolean
          }
        | undefined
    loadSearchResultsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSearchResultsSuccess: (
        data: SurveyDataState,
        payload?:
            | {
                  debounce?: boolean
              }
            | undefined
    ) => {
        data: SurveyDataState
        payload?:
            | {
                  debounce?: boolean
              }
            | undefined
    }
    loadSurveys: () => any
    loadSurveysFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSurveysSuccess: (
        data: SurveyDataState,
        payload?: any
    ) => {
        data: SurveyDataState
        payload?: any
    }
    setIsAppearanceModalOpen: (isOpen: boolean) => {
        isOpen: boolean
    }
    setPreferredEditor: (editor: 'full' | 'guided') => {
        editor: 'full' | 'guided'
    }
    setSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    setSurveyToDuplicate: (survey: Survey | null) => {
        survey: Survey | null
    }
    setSurveysFilters: (
        filters: Partial<SurveysFilters>,
        replace?: boolean
    ) => {
        filters: Partial<SurveysFilters>
        replace: boolean | undefined
    }
    setTab: (tab: SurveysTabs) => {
        tab: SurveysTabs
    }
    updateSurvey: ({
        id,
        updatePayload,
        intentContext,
    }: {
        id: string
        intentContext?: ProductIntentContext
        updatePayload: any
    }) => {
        id: string
        updatePayload: any
        intentContext?: ProductIntentContext
    }
    updateSurveyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateSurveySuccess: (
        data: {
            searchSurveys: Survey[]
            searchSurveysCount: number
            surveys: Survey[]
            surveysCount: number
        },
        payload?: {
            id: string
            updatePayload: any
            intentContext?: ProductIntentContext
        }
    ) => {
        data: {
            searchSurveys: Survey[]
            searchSurveysCount: number
            surveys: Survey[]
            surveysCount: number
        }
        payload?: {
            id: string
            updatePayload: any
            intentContext?: ProductIntentContext
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveysLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        searchedSurveys: (data: SurveyDataState, searchTerm: string) => Survey[]
        surveysStylingAvailable: (
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
        ) => boolean
        formBuilderEnabled: (enabledFlags: FeatureFlagsSet) => boolean
        globalSurveyAppearanceConfigAvailable: (
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
        ) => boolean
        showSurveysDisabledBanner: (currentTeam: TeamPublicType | TeamType | null) => boolean
    }
}

export type surveysLogicType = MakeLogicType<
    surveysLogicValues,
    surveysLogicActions,
    Record<string, any>,
    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(() => ({
        values: [
            userLogic,
            ['hasAvailableFeature'],
            teamLogic,
            ['currentTeam', 'currentTeamLoading'],
            enabledFlagLogic,
            ['featureFlags as enabledFlags'],
            surveysSdkLogic,
            ['teamSdkVersions'],
        ],
        actions: [teamLogic, ['loadCurrentTeam', 'addProductIntent']],
    })),
    actions({
        setIsAppearanceModalOpen: (isOpen: boolean) => ({ isOpen }),
        setSearchTerm: (searchTerm: string) => ({ searchTerm }),
        setSurveysFilters: (filters: Partial<SurveysFilters>, replace?: boolean) => ({ filters, replace }),
        setTab: (tab: SurveysTabs) => ({ tab }),
        loadNextPage: true,
        loadNextSearchPage: true,
        setSurveyToDuplicate: (survey: Survey | null) => ({ survey }),
        setPreferredEditor: (editor: 'guided' | 'full') => ({ editor }),
        handleMaxSurveyCreated: (
            toolOutput: {
                survey_id?: string
                survey_name?: string
                survey_type?: string
                error?: string
                error_message?: string
            },
            source: SURVEY_CREATED_SOURCE
        ) => ({ toolOutput, source }),
    }),
    loaders(({ values, actions, cache }) => ({
        data: {
            __default: {
                surveys: [] as Survey[],
                surveysCount: 0,
                searchSurveys: [] as Survey[],
                searchSurveysCount: 0,
            } as SurveyDataState,
            loadSurveys: async () => {
                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(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 (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(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(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) => {
                const surveyId = String(id)
                await api.surveys.delete(surveyId)
                deleteFromTree('survey', surveyId)
                return {
                    ...values.data,
                    surveys: deleteSurvey(values.data.surveys, id),
                    searchSurveys: deleteSurvey(values.data.searchSurveys, id),
                }
            },
            updateSurvey: async ({
                id,
                updatePayload,
                intentContext,
            }: {
                id: string
                updatePayload: any
                intentContext?: ProductIntentContext
            }) => {
                const updatedSurvey = await api.surveys.update(id, { ...updatePayload })
                if (intentContext) {
                    actions.addProductIntent({
                        product_type: ProductKey.SURVEYS,
                        intent_context: intentContext,
                        metadata: { survey_id: id },
                    })
                }
                return {
                    ...values.data,
                    surveys: updateSurvey(values.data.surveys, id, updatedSurvey),
                    searchSurveys: updateSurvey(values.data.searchSurveys, id, updatedSurvey),
                }
            },
        },
        surveysResponsesCount: {
            __default: {} as { [key: string]: number },
            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: {
            __default: null as Survey | null,
            duplicateSurvey: async (survey: Survey) => {
                const payload = duplicateExistingSurvey(survey)
                const createdSurvey = await api.surveys.create(sanitizeSurvey(payload))

                lemonToast.success('Survey duplicated', {
                    toastId: `survey-duplicated-${createdSurvey.id}`,
                    button: {
                        label: 'View survey',
                        action: () => {
                            router.actions.push(urls.survey(createdSurvey.id))
                        },
                    },
                })

                actions.setSurveyToDuplicate(null)
                actions.addProductIntent({
                    product_type: ProductKey.SURVEYS,
                    intent_context: ProductIntentContext.SURVEY_DUPLICATED,
                    metadata: {
                        survey_id: createdSurvey.id,
                    },
                })

                return createdSurvey
            },
            duplicateToProjects: async ({ survey, targetTeamIds }: { survey: Survey; targetTeamIds: number[] }) => {
                const response = await api.surveys.duplicateToProjects(survey.id, targetTeamIds)

                lemonToast.success(`Survey duplicated to ${pluralize(response.count, 'project')}`, {
                    toastId: `survey-bulk-duplicated-${survey.id}`,
                })

                actions.addProductIntent({
                    product_type: ProductKey.SURVEYS,
                    intent_context: ProductIntentContext.SURVEY_BULK_DUPLICATED,
                    metadata: {
                        survey_id: survey.id,
                        target_team_ids: targetTeamIds,
                        bulk_operation: true,
                    },
                })

                actions.setSurveyToDuplicate(null)
                return survey
            },
        },
    })),
    reducers({
        isAppearanceModalOpen: [
            false,
            {
                setIsAppearanceModalOpen: (_, { isOpen }) => isOpen,
            },
        ],
        tab: [
            SurveysTabs.Active as SurveysTabs,
            {
                setTab: (_, { tab }) => tab,
            },
        ],
        searchTerm: [
            '',
            {
                setSearchTerm: (_, { searchTerm }) => searchTerm,
            },
        ],
        filters: [
            {
                archived: false,
                type: 'any',
                status: 'any',
                created_by: null,
            } as Partial<SurveysFilters>,
            {
                setSurveysFilters: (state, { filters }) => {
                    return { ...state, ...filters }
                },
            },
        ],
        hasNextPage: [
            true as boolean,
            {
                loadSurveysSuccess: (_, { data }) => hasMorePages(data.surveys, data.surveysCount),
                loadNextPageSuccess: (_, { data }) => hasMorePages(data.surveys, data.surveysCount),
            },
        ],
        hasNextSearchPage: [
            false as boolean,
            {
                loadSearchResultsSuccess: (_, { data }) => hasMorePages(data.searchSurveys, data.searchSurveysCount),
                loadNextSearchPageSuccess: (_, { data }) => hasMorePages(data.searchSurveys, data.searchSurveysCount),
            },
        ],
        surveyToDuplicate: [
            null as Survey | null,
            {
                setSurveyToDuplicate: (_, { survey }) => survey,
            },
        ],
        // Remembers which editor (guided wizard vs full editor) the user last
        // chose. Used on "new survey" landing pages to redirect to their
        // preferred editor automatically.
        preferredEditor: [
            'guided' as 'guided' | 'full',
            { persist: true },
            {
                setPreferredEditor: (_, { editor }) => editor,
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        deleteSurveySuccess: (_, __, action) => {
            lemonToast.success('Survey deleted')
            router.actions.push(urls.surveys())
            actions.addProductIntent({
                product_type: ProductKey.SURVEYS,
                intent_context: ProductIntentContext.SURVEY_DELETED,
                metadata: {
                    survey_id: String(action.payload),
                },
            })
        },
        updateSurveySuccess: () => {
            lemonToast.success('Survey updated')
            actions.loadCurrentTeam()
        },
        duplicateSurveySuccess: () => {
            actions.loadSurveys()
        },
        duplicateToProjectsSuccess: () => {
            actions.loadSurveys()
        },
        setSurveysFilters: () => {
            if (values.searchTerm.trim()) {
                actions.loadSearchResults(undefined)
            } else {
                actions.loadSurveys()
            }
        },
        loadSurveysSuccess: () => {
            actions.loadCurrentTeam()
        },
        loadResponsesCountSuccess: () => {
            if (Object.values(values.surveysResponsesCount).some((count) => count > 0)) {
                globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CollectSurveyResponses)
            }
        },
        setTab: ({ tab }) => {
            actions.setSurveysFilters({ ...values.filters, archived: tab === SurveysTabs.Archived })
        },
        handleMaxSurveyCreated: ({ toolOutput, source }) => {
            actions.addProductIntent({
                product_type: ProductKey.SURVEYS,
                intent_context: ProductIntentContext.SURVEY_CREATED,
                metadata: {
                    survey_id: toolOutput.survey_id,
                    source,
                    created_successfully: !toolOutput?.error,
                },
            })

            if (toolOutput?.error || !toolOutput?.survey_id) {
                captureMaxAISurveyCreationException(toolOutput.error, source)
                return
            }

            actions.loadSurveys()
            if (toolOutput.survey_type === 'popover') {
                router.actions.push(urls.surveyWizard(toolOutput.survey_id))
            } else {
                router.actions.push(urls.survey(toolOutput.survey_id) + '?edit=true')
            }
        },
        setSearchTerm: () => {
            if (values.searchTerm.trim()) {
                actions.loadSearchResults({ debounce: true })
            } else {
                actions.loadSurveys()
            }
        },
    })),
    selectors({
        searchedSurveys: [
            (selectors) => [selectors.data, selectors.searchTerm],
            (data: SurveyDataState, searchTerm: string) => (searchTerm.trim() ? data.searchSurveys : data.surveys),
        ],
        breadcrumbs: [
            () => [],
            (): Breadcrumb[] => [
                {
                    key: Scene.Surveys,
                    name: sceneConfigurations[Scene.Surveys].name || 'Surveys',
                    path: urls.surveys(),
                    iconType: sceneConfigurations[Scene.Surveys].iconType || 'default_icon_type',
                },
            ],
        ],
        surveysStylingAvailable: [
            (s) => [s.hasAvailableFeature],
            (hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean) =>
                hasAvailableFeature(AvailableFeature.SURVEYS_STYLING),
        ],
        formBuilderEnabled: [
            (s) => [s.enabledFlags],
            (enabledFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet) =>
                !!enabledFlags[FEATURE_FLAGS.SURVEYS_FORM_BUILDER],
        ],
        globalSurveyAppearanceConfigAvailable: [
            (s) => [s.hasAvailableFeature],
            (hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean) =>
                hasAvailableFeature(AvailableFeature.SURVEYS_STYLING),
        ],
        showSurveysDisabledBanner: [
            (s) => [s.currentTeam],
            (currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType) => {
                return !currentTeam?.surveys_opt_in
            },
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            () => [],
            (): SidePanelSceneContext => ({
                activity_scope: ActivityScope.SURVEY,
            }),
        ],
    }),
    actionToUrl(({ values }) => ({
        setTab: () => {
            return [
                router.values.location.pathname,
                { ...router.values.searchParams, tab: values.tab },
                router.values.hashParams,
            ]
        },
        setSearchTerm: () => {
            const searchParams = { ...router.values.searchParams }
            if (values.searchTerm) {
                searchParams.search = values.searchTerm
            } else {
                delete searchParams.search
            }
            return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
        },
    })),
    urlToAction(({ actions, values }) => ({
        [urls.surveys()]: (_, { tab, search }) => {
            if (tab) {
                actions.setTab(tab)
            }
            // The router parses purely-numeric query params into numbers, so coerce to a string.
            const nextSearchTerm = search != null ? String(search) : ''
            if (nextSearchTerm !== values.searchTerm) {
                actions.setSearchTerm(nextSearchTerm)
            }
            actions.addProductIntent({
                product_type: ProductKey.SURVEYS,
                intent_context: ProductIntentContext.SURVEYS_VIEWED,
            })
        },
    })),
    afterMount(({ actions }) => {
        actions.loadSurveys()
    }),
])