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.

23.4 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import type { FieldName } from 'kea-forms/lib/index'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

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

import api from 'lib/api'
import { ApiError } from 'lib/api-error'
import { dayjs } from 'lib/dayjs'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { Breadcrumb, LinkSurveyQuestion, Survey, SurveyQuestionType, SurveySchedule, SurveyType } from '~/types'

import { reportSurveyCreated, reportSurveyEdited } from 'products/surveys/frontend/surveyUsage'

import type { ProductIntentProperties } from '../../../lib/utils/product-intents'
import type { TeamPublicType, TeamType } from '../../../types'
import {
    SURVEY_CREATED_SOURCE,
    SurveyTemplate,
    SurveyTemplateMode,
    SurveyTemplateType,
    defaultSurveyAppearance,
    defaultSurveyTemplates,
    surveyThemes,
} from '../constants'
import type { NewSurvey } from '../constants'
import { surveyLogic } from '../surveyLogic'
import { surveysLogic } from '../surveysLogic'

export type WizardStep = 'template' | 'questions' | 'where' | 'when' | 'appearance' | 'success'

// Re-exported for convenience — the canonical definition lives in ../constants.
export type { SurveyTemplateMode } from '../constants'

// Main flow steps (appearance is optional, branched from 'when')
const WIZARD_STEPS: WizardStep[] = ['template', 'questions', 'where', 'when']

// Core templates to show prominently, per template mode.
const CORE_TEMPLATE_TYPES: Record<SurveyTemplateMode, SurveyTemplateType[]> = {
    in_app: [SurveyTemplateType.NPS, SurveyTemplateType.CSAT, SurveyTemplateType.PMF, SurveyTemplateType.OpenFeedback],
    hosted: [
        SurveyTemplateType.UserResearchIntake,
        SurveyTemplateType.ProductResearch,
        SurveyTemplateType.NPS,
        SurveyTemplateType.CCR,
    ],
}

function templateMatchesMode(template: SurveyTemplate, mode: SurveyTemplateMode): boolean {
    return !template.modes || template.modes.includes(mode)
}

function errorDetailOr(error: unknown, fallback: string): string {
    return (error instanceof ApiError && error.detail) || fallback
}

export interface SurveyWizardLogicProps {
    id: string // 'new' for new surveys, or a UUID for editing
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyWizardLogicValues {
    survey: NewSurvey | Survey // surveyLogic
    surveyChanged: boolean // surveyLogic
    surveyLoading: boolean // surveyLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    breadcrumbs: Breadcrumb[]
    coreTemplates: SurveyTemplate[]
    createdSurvey: Survey | null
    currentStep: WizardStep
    currentStepHasErrors: boolean
    otherTemplates: SurveyTemplate[]
    recommendedFrequency: {
        label: string
        reason: string
        value: string
    }
    selectedTemplate: SurveyTemplate | null
    stepNumber: number
    stepValidationErrors: Record<WizardStep, string[]>
    surveyLaunching: boolean
    surveySaving: boolean
    templateMode: SurveyTemplateMode
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyWizardLogicActions {
    loadSurvey: () => any // surveyLogic
    resetSurvey: (values?: NewSurvey | Survey | undefined) => {
        values?: NewSurvey | Survey
    } // surveyLogic
    setSurveyValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    } // surveyLogic
    loadSurveys: () => any // surveysLogic
    addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
    launchSurvey: () => {
        value: true
    }
    launchSurveyFailure: (error: string) => {
        error: string
    }
    launchSurveySuccess: (survey: Survey) => {
        survey: Survey
    }
    nextStep: () => {
        value: true
    }
    prevStep: () => {
        value: true
    }
    resetWizard: () => {
        value: true
    }
    restoreDefaultQuestions: () => {
        value: true
    }
    saveDraft: () => {
        value: true
    }
    saveDraftFailure: (error: string) => {
        error: string
    }
    saveDraftSuccess: (survey: Survey) => {
        survey: Survey
    }
    selectTemplate: (template: SurveyTemplate) => {
        template: SurveyTemplate
    }
    setStep: (step: WizardStep) => {
        step: WizardStep
    }
    setTemplateMode: (mode: SurveyTemplateMode) => {
        mode: SurveyTemplateMode
    }
    updateSurvey: () => {
        value: true
    }
    updateSurveyFailure: (error: string) => {
        error: string
    }
    updateSurveySuccess: (survey: Survey) => {
        survey: Survey
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface surveyWizardLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        coreTemplates: (templateMode: SurveyTemplateMode) => SurveyTemplate[]
        otherTemplates: (templateMode: SurveyTemplateMode) => SurveyTemplate[]
        stepNumber: (currentStep: WizardStep) => number
        breadcrumbs: (survey: NewSurvey | Survey) => Breadcrumb[]
        stepValidationErrors: (survey: NewSurvey | Survey) => Record<WizardStep, string[]>
        currentStepHasErrors: (stepValidationErrors: Record<WizardStep, string[]>, currentStep: WizardStep) => boolean
        recommendedFrequency: (selectedTemplate: SurveyTemplate | null) => {
            label: string
            reason: string
            value: string
        }
    }
}

export type surveyWizardLogicType = MakeLogicType<
    surveyWizardLogicValues,
    surveyWizardLogicActions,
    SurveyWizardLogicProps,
    surveyWizardLogicMeta
>

export const surveyWizardLogic = kea<surveyWizardLogicType>([
    path(['scenes', 'surveys', 'wizard', 'surveyWizardLogic']),

    props({} as SurveyWizardLogicProps),

    key((props) => props.id),

    connect((props: SurveyWizardLogicProps) => ({
        actions: [
            surveyLogic({ id: props.id }),
            ['setSurveyValue', 'resetSurvey', 'loadSurvey'],
            surveysLogic,
            ['loadSurveys'],
            teamLogic,
            ['addProductIntent'],
        ],
        values: [
            surveyLogic({ id: props.id }),
            ['survey', 'surveyChanged', 'surveyLoading'],
            teamLogic,
            ['currentTeam'],
        ],
    })),

    actions({
        setStep: (step: WizardStep) => ({ step }),
        nextStep: true,
        prevStep: true,
        resetWizard: true,
        selectTemplate: (template: SurveyTemplate) => ({ template }),
        setTemplateMode: (mode: SurveyTemplateMode) => ({ mode }),
        restoreDefaultQuestions: true,
        launchSurvey: true,
        launchSurveySuccess: (survey: Survey) => ({ survey }),
        launchSurveyFailure: (error: string) => ({ error }),
        saveDraft: true,
        saveDraftSuccess: (survey: Survey) => ({ survey }),
        saveDraftFailure: (error: string) => ({ error }),
        updateSurvey: true,
        updateSurveySuccess: (survey: Survey) => ({ survey }),
        updateSurveyFailure: (error: string) => ({ error }),
    }),

    reducers(({ props }) => ({
        currentStep: [
            // Start at 'questions' when editing, 'template' when creating new
            (props.id === 'new' ? 'template' : 'questions') as WizardStep,
            {
                setStep: (_, { step }) => step,
                nextStep: (state) => {
                    const currentIndex = WIZARD_STEPS.indexOf(state)
                    return WIZARD_STEPS[Math.min(currentIndex + 1, WIZARD_STEPS.length - 1)]
                },
                prevStep: (state) => {
                    const currentIndex = WIZARD_STEPS.indexOf(state)
                    return WIZARD_STEPS[Math.max(currentIndex - 1, 0)]
                },
                resetWizard: () => (props.id === 'new' ? 'template' : 'questions'),
                selectTemplate: () => 'questions',
            },
        ],
        selectedTemplate: [
            null as SurveyTemplate | null,
            {
                selectTemplate: (_, { template }) => template,
                resetWizard: () => null,
            },
        ],
        templateMode: [
            'in_app' as SurveyTemplateMode,
            {
                setTemplateMode: (_, { mode }) => mode,
                resetWizard: () => 'in_app' as SurveyTemplateMode,
            },
        ],
        createdSurvey: [
            null as Survey | null,
            {
                launchSurveySuccess: (_, { survey }) => survey,
                updateSurveySuccess: (_, { survey }) => survey,
                resetWizard: () => null,
            },
        ],
        surveyLaunching: [
            false,
            {
                launchSurvey: () => true,
                launchSurveySuccess: () => false,
                launchSurveyFailure: () => false,
            },
        ],
        surveySaving: [
            false,
            {
                saveDraft: () => true,
                saveDraftSuccess: () => false,
                saveDraftFailure: () => false,
                updateSurvey: () => true,
                updateSurveySuccess: () => false,
                updateSurveyFailure: () => false,
            },
        ],
    })),

    selectors({
        coreTemplates: [
            (s) => [s.templateMode],
            (mode: SurveyTemplateMode): SurveyTemplate[] => {
                const coreTypes = CORE_TEMPLATE_TYPES[mode]
                // Preserve the order declared in CORE_TEMPLATE_TYPES so featured cards stay positioned.
                return coreTypes
                    .map((type) => defaultSurveyTemplates.find((t) => t.templateType === type))
                    .filter((t): t is SurveyTemplate => !!t && templateMatchesMode(t, mode))
            },
        ],
        otherTemplates: [
            (s) => [s.templateMode],
            (mode: SurveyTemplateMode): SurveyTemplate[] => {
                const coreTypes = new Set<SurveyTemplateType>(CORE_TEMPLATE_TYPES[mode])
                return defaultSurveyTemplates.filter(
                    (t) => !coreTypes.has(t.templateType) && templateMatchesMode(t, mode)
                )
            },
        ],
        stepNumber: [(s) => [s.currentStep], (currentStep: WizardStep): number => WIZARD_STEPS.indexOf(currentStep)],
        breadcrumbs: [
            (s) => [s.survey],
            (survey: Survey): Breadcrumb[] => [
                {
                    key: Scene.Surveys,
                    name: 'Surveys',
                    path: urls.surveys(),
                    iconType: 'survey',
                },
                {
                    key: [Scene.SurveyWizard, survey?.id || 'new'],
                    name: survey?.name || 'New survey',
                    iconType: 'survey',
                },
            ],
        ],
        stepValidationErrors: [
            (s) => [s.survey],
            (survey: Survey): Record<WizardStep, string[]> => {
                const errors: Record<WizardStep, string[]> = {
                    template: [],
                    questions: [],
                    where: [],
                    when: [],
                    appearance: [],
                    success: [],
                }

                // Validate questions step
                if (survey.questions) {
                    for (const question of survey.questions) {
                        if (question.type === SurveyQuestionType.Link) {
                            const linkQuestion = question as LinkSurveyQuestion
                            const link = linkQuestion.link || ''
                            if (link && !link.startsWith('https://') && !link.startsWith('mailto:')) {
                                errors.questions.push('Link URLs must start with https:// or mailto:')
                                break // Only show one error
                            }
                        }
                    }
                }

                return errors
            },
        ],
        currentStepHasErrors: [
            (s) => [s.stepValidationErrors, s.currentStep],
            (errors: Record<WizardStep, string[]>, currentStep: WizardStep): boolean => {
                return errors[currentStep]?.length > 0
            },
        ],
        recommendedFrequency: [
            (s) => [s.selectedTemplate],
            (template: SurveyTemplate | null): { value: string; label: string; reason: string } => {
                const templateType = template?.templateType
                if (templateType?.includes('NPS') || templateType?.includes('PMF')) {
                    return {
                        value: 'quarterly',
                        label: 'Every 3 months',
                        reason: 'Relationship metrics work best quarterly',
                    }
                }
                if (templateType?.includes('CSAT') || templateType?.includes('CES')) {
                    return {
                        value: 'monthly',
                        label: 'Every month',
                        reason: 'Transactional surveys can be more frequent',
                    }
                }
                if (
                    templateType?.includes('Onboarding') ||
                    templateType?.includes('Attribution') ||
                    templateType?.includes('Exit') ||
                    templateType?.includes('Announcement')
                ) {
                    return { value: 'once', label: 'Once ever', reason: 'One-time feedback collection' }
                }
                return { value: 'monthly', label: 'Every month', reason: 'General feedback cadence' }
            },
        ],
    }),

    listeners(({ actions, values, props }) => ({
        selectTemplate: ({ template }) => {
            const isHostedMode = values.templateMode === 'hosted'
            const timestamp = dayjs().format('YYYY-MM-DD HH:mm')
            actions.setSurveyValue('name', `${template.templateType} (${timestamp})`)
            actions.setSurveyValue('description', template.description || '')
            actions.setSurveyValue(
                'type',
                isHostedMode ? SurveyType.ExternalSurvey : template.type || SurveyType.Popover
            )
            actions.setSurveyValue('questions', template.questions)

            // Apply Clean theme by default (works well on most sites, and users without
            // styling access are stuck with the default, so light-friendly is safer)
            // Only take behavioral (non-color) properties from template appearance
            const defaultTheme = surveyThemes.find((t) => t.id === 'clean')
            const themeAppearance = defaultTheme?.appearance || {}

            // Extract only behavioral properties from template (not colors)
            const templateBehavior = template.appearance
                ? {
                      displayThankYouMessage: template.appearance.displayThankYouMessage,
                      thankYouMessageHeader: template.appearance.thankYouMessageHeader,
                      displayIntroScreen: template.appearance.displayIntroScreen,
                      introScreenHeader: template.appearance.introScreenHeader,
                      introScreenDescription: template.appearance.introScreenDescription,
                      introScreenDescriptionContentType: template.appearance.introScreenDescriptionContentType,
                      introScreenButtonText: template.appearance.introScreenButtonText,
                      position: template.appearance.position,
                      shuffleQuestions: template.appearance.shuffleQuestions,
                      surveyPopupDelaySeconds: template.appearance.surveyPopupDelaySeconds,
                  }
                : {}
            // Remove undefined values
            const cleanTemplateBehavior = Object.fromEntries(
                Object.entries(templateBehavior).filter(([_, v]) => v !== undefined)
            )

            actions.setSurveyValue('appearance', {
                ...defaultSurveyAppearance,
                ...themeAppearance,
                ...values.currentTeam?.survey_config?.appearance,
                ...cleanTemplateBehavior,
            })

            const frequencyToDays: Record<string, number | undefined> = {
                once: undefined,
                yearly: 365,
                quarterly: 90,
                monthly: 30,
            }
            const { value: frequencyValue } = values.recommendedFrequency
            const isOnce = frequencyValue === 'once'
            actions.setSurveyValue('schedule', isOnce ? SurveySchedule.Once : SurveySchedule.Recurring)
            actions.setSurveyValue('iteration_count', isOnce ? 0 : 10)
            actions.setSurveyValue('iteration_frequency_days', isOnce ? 0 : frequencyToDays[frequencyValue])
            actions.setSurveyValue('conditions', template.conditions ?? null)

            posthog.capture('survey template clicked', {
                template: template.templateType,
                source: SURVEY_CREATED_SOURCE.SURVEY_WIZARD,
            })

            // Hosted surveys don't have a guided wizard — route to the dedicated editor.
            if (isHostedMode) {
                router.actions.push(props.id === 'new' ? urls.survey('new') : `${urls.survey(props.id)}?edit=true`)
            }
        },
        restoreDefaultQuestions: () => {
            const template = values.selectedTemplate
            if (template) {
                actions.setSurveyValue('questions', template.questions)
                lemonToast.success('Questions restored to defaults')
            }
        },
        launchSurvey: async () => {
            try {
                const surveyData = {
                    ...values.survey,
                    start_date: new Date().toISOString(),
                }
                const createdSurvey = await api.surveys.create(surveyData)
                actions.launchSurveySuccess(createdSurvey)
            } catch (e) {
                actions.launchSurveyFailure(String(e))
                lemonToast.error(errorDetailOr(e, 'Failed to create survey'))
            }
        },
        launchSurveySuccess: ({ survey }) => {
            lemonToast.success(`Survey ${survey.name} created`)
            actions.loadSurveys()
            reportSurveyCreated(survey, false, 'wizard')
            actions.addProductIntent({
                product_type: ProductKey.SURVEYS,
                intent_context: ProductIntentContext.SURVEY_CREATED,
                metadata: {
                    survey_id: survey.id,
                    source: SURVEY_CREATED_SOURCE.SURVEY_WIZARD,
                },
            })
            actions.addProductIntent({
                product_type: ProductKey.SURVEYS,
                intent_context: ProductIntentContext.SURVEY_LAUNCHED,
                metadata: {
                    survey_id: survey.id,
                    source: SURVEY_CREATED_SOURCE.SURVEY_WIZARD,
                },
            })
            actions.setStep('success')
        },
        saveDraft: async () => {
            try {
                const createdSurvey = await api.surveys.create(values.survey)
                actions.saveDraftSuccess(createdSurvey)
            } catch (e) {
                actions.saveDraftFailure(String(e))
                lemonToast.error(errorDetailOr(e, 'Failed to save draft'))
            }
        },
        saveDraftSuccess: ({ survey }) => {
            lemonToast.success(`Survey "${survey.name}" saved as draft`)
            actions.loadSurveys()
            reportSurveyCreated(survey, false, 'wizard')
            actions.addProductIntent({
                product_type: ProductKey.SURVEYS,
                intent_context: ProductIntentContext.SURVEY_CREATED,
                metadata: {
                    survey_id: survey.id,
                    source: SURVEY_CREATED_SOURCE.SURVEY_WIZARD,
                },
            })
            router.actions.push(urls.survey(survey.id))
        },
        updateSurvey: async () => {
            try {
                const updatedSurvey = await api.surveys.update(props.id, values.survey)
                actions.updateSurveySuccess(updatedSurvey)
            } catch (e) {
                actions.updateSurveyFailure(String(e))
                lemonToast.error(errorDetailOr(e, 'Failed to update survey'))
            }
        },
        updateSurveySuccess: ({ survey }) => {
            lemonToast.success(`Survey "${survey.name}" updated`)
            actions.loadSurveys()
            reportSurveyEdited(survey)
            router.actions.push(urls.survey(survey.id))
        },
    })),

    urlToAction(({ actions, props, values }) => ({
        [urls.surveyWizard(props.id)]: (_, searchParams) => {
            const templateParam = searchParams.template
            if (templateParam && props.id === 'new') {
                const matchedTemplate = defaultSurveyTemplates.find((t) => t.templateType === templateParam)
                if (matchedTemplate) {
                    actions.resetSurvey()
                    actions.selectTemplate(matchedTemplate)
                }
            } else if (props.id === 'new' && values.currentStep === 'success') {
                // Reset wizard when navigating back after a successful launch,
                // since the scene-level logic mount keeps state alive across navigations
                actions.resetWizard()
                actions.resetSurvey()
            }
        },
    })),

    afterMount(({ actions, props, values }) => {
        // Preserve any in-memory edits when re-mounting on the same survey id (e.g.
        // navigating between the full editor and the wizard). surveyChanged is
        // in-memory only, so a fresh session can never trigger this branch.
        const shouldPreserveLocalChanges = values.surveyChanged && values.survey.id === props.id

        if (props.id === 'new') {
            if (shouldPreserveLocalChanges) {
                actions.setStep('questions')
                return
            }

            // Templates set both name AND questions, while default NEW_SURVEY has empty name
            const hasTemplateSelected = values.survey?.name && values.survey?.questions?.length > 0
            if (hasTemplateSelected) {
                actions.setStep('questions')
            } else {
                actions.resetWizard()
                actions.resetSurvey()
            }
        } else if (!shouldPreserveLocalChanges) {
            actions.loadSurvey()
        }
    }),

    beforeUnmount(({ actions, props }) => {
        actions.resetWizard()
        // For an in-progress "new" survey, preserve the in-memory draft only if the
        // user is navigating to the other survey-editor view for the same id (full
        // editor for new). Anywhere else (list, dashboards, etc.) means the user
        // abandoned the draft, so we clear it. Using `endsWith` so this still works
        // when the app is mounted under a project-scoped path (`/project/<id>/...`).
        if (props.id === 'new') {
            const destination = router.values.location.pathname
            const stayingInNewSurveyEditor =
                destination.endsWith(urls.survey('new')) || destination.endsWith(urls.surveyWizard('new'))
            if (!stayingInNewSurveyEditor) {
                actions.resetSurvey()
            }
        }
    }),
])