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.6 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
import { loaders } from 'kea-loaders'

import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
import { teamLogic } from 'scenes/teamLogic'

import { ProductKey } from '~/queries/schema/schema-general'

import { featureFlagsList } from 'products/feature_flags/frontend/generated/api'
import { FeatureFlagsListArchived } from 'products/feature_flags/frontend/generated/api.schemas'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagsSetupLogicValues {
    setupStatus: ProductSetupStatus // productSetupStatusLogic
    currentProjectId: number | string // teamLogic
    hasAnyFlag: boolean | null
    hasAnyFlagLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagsSetupLogicActions {
    setDetectedStatus: (status: ProductSetupStatus) => {
        status: ProductSetupStatus
    } // productSetupStatusLogic
    loadHasAnyFlag: (_: void) => void
    loadHasAnyFlagFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadHasAnyFlagSuccess: (
        hasAnyFlag: boolean,
        payload?: void
    ) => {
        hasAnyFlag: boolean
        payload?: void
    }
}

export type featureFlagsSetupLogicType = MakeLogicType<featureFlagsSetupLogicValues, featureFlagsSetupLogicActions>

/**
 * Setup detection for the feature flags empty state. Flags are a creation-first
 * product, so "set up" simply means the project has at least one flag - no event
 * or traffic signal involved. Re-checks on every mount (the scene gate mounts it),
 * which covers returning from the flag creation page.
 */
export const featureFlagsSetupLogic = kea<featureFlagsSetupLogicType>([
    path(['products', 'feature_flags', 'frontend', 'emptyState', 'featureFlagsSetupLogic']),
    connect(() => ({
        actions: [productSetupStatusLogic({ productKey: ProductKey.FEATURE_FLAGS }), ['setDetectedStatus']],
        values: [
            productSetupStatusLogic({ productKey: ProductKey.FEATURE_FLAGS }),
            ['status as setupStatus'],
            teamLogic,
            ['currentProjectId'],
        ],
    })),
    loaders(({ values }) => ({
        hasAnyFlag: [
            null as boolean | null,
            {
                loadHasAnyFlag: async (_: void, breakpoint): Promise<boolean> => {
                    const live = await featureFlagsList(String(values.currentProjectId), { limit: 1 })
                    breakpoint()
                    if (live.count > 0) {
                        return true
                    }
                    // The list excludes archived flags unless asked for them, and no value of
                    // `archived` returns both, so a project that archived all of its flags would
                    // count zero and lose the scene it unarchives them from.
                    const archived = await featureFlagsList(String(values.currentProjectId), {
                        limit: 1,
                        archived: FeatureFlagsListArchived.True,
                    })
                    breakpoint()
                    return archived.count > 0
                },
            },
        ],
    })),
    listeners(({ actions, values }) => ({
        // Undo of a deleted flag brings it back without remounting the gate, so no flag check runs on its own.
        // The flag list reloads after Undo, and that reload is the signal to check again.
        [featureFlagsLogic.actionTypes.loadFeatureFlagsSuccess]: ({ featureFlags }) => {
            if (values.setupStatus === 'has-data') {
                return
            }
            if (featureFlags.count > 0) {
                actions.setDetectedStatus('has-data')
            } else {
                actions.loadHasAnyFlag()
            }
        },
        loadHasAnyFlagSuccess: ({ hasAnyFlag }) => {
            actions.setDetectedStatus(hasAnyFlag ? 'has-data' : 'needs-setup')
        },
        loadHasAnyFlagFailure: () => {
            // Never strand the gate on its spinner: if nothing has answered yet, fail
            // open to the real scene. Don't downgrade an existing answer on a blip.
            if (values.setupStatus === 'loading') {
                actions.setDetectedStatus('unknown')
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadHasAnyFlag()
    }),
])