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.

4.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers } from 'kea'
import { router } from 'kea-router'

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import type { Experiment } from '~/types'

export interface CreateDraftExperimentFromFlagLogicProps {
    featureFlagKey: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface createDraftExperimentFromFlagLogicValues {
    currentProjectId: number | string // teamLogic
    error: string | null
    experimentDescription: string
    experimentName: string
    isLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface createDraftExperimentFromFlagLogicActions {
    createDraftExperiment: () => {
        value: true
    }
    createDraftExperimentFailure: (error: string) => {
        error: string
    }
    createDraftExperimentSuccess: (experiment: Experiment) => {
        experiment: Experiment
    }
    setExperimentDescription: (description: string) => {
        description: string
    }
    setExperimentName: (name: string) => {
        name: string
    }
}

export type createDraftExperimentFromFlagLogicType = MakeLogicType<
    createDraftExperimentFromFlagLogicValues,
    createDraftExperimentFromFlagLogicActions,
    CreateDraftExperimentFromFlagLogicProps
>

export const createDraftExperimentFromFlagLogic = kea<createDraftExperimentFromFlagLogicType>([
    path(['scenes', 'experiments', 'ExperimentTabContent', 'createDraftExperimentFromFlagLogic']),
    props({} as CreateDraftExperimentFromFlagLogicProps),

    connect({
        values: [teamLogic, ['currentProjectId']],
    }),

    actions({
        setExperimentName: (name: string) => ({ name }),
        setExperimentDescription: (description: string) => ({ description }),
        createDraftExperiment: true,
        createDraftExperimentSuccess: (experiment: Experiment) => ({ experiment }),
        createDraftExperimentFailure: (error: string) => ({ error }),
    }),

    reducers({
        experimentName: ['', { setExperimentName: (_, { name }) => name }],
        experimentDescription: ['', { setExperimentDescription: (_, { description }) => description }],
        isLoading: [
            false,
            {
                createDraftExperiment: () => true,
                createDraftExperimentSuccess: () => false,
                createDraftExperimentFailure: () => false,
            },
        ],
        error: [
            null as string | null,
            {
                createDraftExperiment: () => null,
                createDraftExperimentFailure: (_, { error }) => error,
                setExperimentName: () => null,
            },
        ],
    }),

    listeners(({ actions, values, props }) => ({
        createDraftExperiment: async () => {
            const name = values.experimentName.trim()

            if (!name) {
                actions.createDraftExperimentFailure('Experiment name is required')
                return
            }

            // No flag config in the payload: the flag already exists, so the experiment links
            // to it as-is (its variants carry over) and explicit config would be rejected.
            const payload = {
                name,
                description: values.experimentDescription.trim() || '',
                type: 'product',
                feature_flag_key: props.featureFlagKey,
                exposure_criteria: {
                    filterTestAccounts: true,
                },
                metrics: [],
                metrics_secondary: [],
                start_date: null,
            }

            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentsCreate() from 'products/experiments/frontend/generated/api' instead.
                const experiment: Experiment = await api.create(
                    `api/projects/${values.currentProjectId}/experiments`,
                    payload
                )
                actions.createDraftExperimentSuccess(experiment)
            } catch (error: any) {
                const errorMessage = error?.detail || 'Failed to create experiment'
                actions.createDraftExperimentFailure(errorMessage)
            }
        },

        createDraftExperimentSuccess: ({ experiment }) => {
            lemonToast.success('Draft experiment created')
            router.actions.push(urls.experiment(experiment.id))
        },

        createDraftExperimentFailure: ({ error }) => {
            lemonToast.error(`Failed to create experiment: ${error}`)
        },
    })),
])