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.

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

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'

import { FeatureFlagFilters, FeatureFlagGroupType } from '~/types'

import type { TeamPublicType, TeamType } from '../../types'
import { uniformAggregationGroupTypeIndex } from './defaultReleaseConditionsUtils'

export interface DefaultReleaseConditionsResponse {
    enabled: boolean
    default_groups: FeatureFlagGroupType[]
}

export async function fetchDefaultReleaseConditions(teamId: number): Promise<DefaultReleaseConditionsResponse> {
    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsDefaultReleaseConditionsRetrieve() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
    return await api.get(`/api/projects/${teamId}/default_release_conditions/`)
}

/**
 * Returns the cached value if already loaded, otherwise fetches it directly.
 * Used in loaders that need default release conditions on mount before the
 * async load from defaultReleaseConditionsLogic has resolved.
 */
export async function resolveDefaultReleaseConditions(
    cached: DefaultReleaseConditionsResponse | null,
    teamId: number | undefined
): Promise<DefaultReleaseConditionsResponse | null> {
    if (cached) {
        return cached
    }
    if (!teamId) {
        return null
    }
    try {
        return await fetchDefaultReleaseConditions(teamId)
    } catch (e) {
        console.warn('Failed to fetch default release conditions:', e)
        return null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface defaultReleaseConditionsLogicValues {
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    defaultReleaseConditions: DefaultReleaseConditionsResponse | null
    defaultReleaseConditionsLoading: boolean
    filtersForEditor: FeatureFlagFilters
    groups: FeatureFlagGroupType[]
    hasChanges: boolean
    isEnabled: boolean
    localEnabled: boolean
    localGroups: FeatureFlagGroupType[] | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface defaultReleaseConditionsLogicActions {
    discardChanges: () => {
        value: true
    }
    loadDefaultReleaseConditions: () => any
    loadDefaultReleaseConditionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDefaultReleaseConditionsSuccess: (
        defaultReleaseConditions: DefaultReleaseConditionsResponse | null,
        payload?: any
    ) => {
        defaultReleaseConditions: DefaultReleaseConditionsResponse | null
        payload?: any
    }
    saveDefaultReleaseConditions: () => any
    saveDefaultReleaseConditionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveDefaultReleaseConditionsSuccess: (
        defaultReleaseConditions: DefaultReleaseConditionsResponse,
        payload?: any
    ) => {
        defaultReleaseConditions: DefaultReleaseConditionsResponse
        payload?: any
    }
    setLocalEnabled: (enabled: boolean) => {
        enabled: boolean
    }
    setLocalGroups: (groups: FeatureFlagGroupType[]) => {
        groups: FeatureFlagGroupType[]
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface defaultReleaseConditionsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isEnabled: (localEnabled: boolean) => boolean
        groups: (localGroups: FeatureFlagGroupType[] | null) => FeatureFlagGroupType[]
        filtersForEditor: (groups: FeatureFlagGroupType[]) => FeatureFlagFilters
        hasChanges: (
            localGroups: FeatureFlagGroupType[] | null,
            localEnabled: boolean,
            defaultReleaseConditions: DefaultReleaseConditionsResponse | null
        ) => boolean
    }
}

export type defaultReleaseConditionsLogicType = MakeLogicType<
    defaultReleaseConditionsLogicValues,
    defaultReleaseConditionsLogicActions,
    Record<string, any>,
    defaultReleaseConditionsLogicMeta
>

export const defaultReleaseConditionsLogic = kea<defaultReleaseConditionsLogicType>([
    path(['scenes', 'feature-flags', 'defaultReleaseConditionsLogic']),

    connect(() => ({
        values: [teamLogic, ['currentTeam']],
    })),

    actions({
        setLocalGroups: (groups: FeatureFlagGroupType[]) => ({ groups }),
        setLocalEnabled: (enabled: boolean) => ({ enabled }),
        discardChanges: true,
    }),

    reducers({
        localGroups: [
            null as FeatureFlagGroupType[] | null,
            {
                setLocalGroups: (_, { groups }) => groups,
                loadDefaultReleaseConditionsSuccess: (_, { defaultReleaseConditions }) =>
                    defaultReleaseConditions?.default_groups ?? [],
            },
        ],
        localEnabled: [
            false,
            {
                setLocalEnabled: (_, { enabled }) => enabled,
                loadDefaultReleaseConditionsSuccess: (_, { defaultReleaseConditions }) =>
                    defaultReleaseConditions?.enabled ?? false,
            },
        ],
    }),

    loaders(({ values }) => ({
        defaultReleaseConditions: [
            null as DefaultReleaseConditionsResponse | null,
            {
                loadDefaultReleaseConditions: async () => {
                    const teamId = values.currentTeam?.id
                    if (!teamId) {
                        return null
                    }
                    return await fetchDefaultReleaseConditions(teamId)
                },

                saveDefaultReleaseConditions: async () => {
                    const teamId = values.currentTeam?.id
                    if (!teamId) {
                        throw new Error('No team selected')
                    }

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsDefaultReleaseConditionsUpdate() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                    return (await api.put(`/api/projects/${teamId}/default_release_conditions/`, {
                        enabled: values.localEnabled,
                        default_groups: values.localGroups ?? [],
                    })) as DefaultReleaseConditionsResponse
                },
            },
        ],
    })),

    listeners(({ actions, values }) => ({
        saveDefaultReleaseConditionsSuccess: () => {
            lemonToast.success('Default release conditions saved')
        },
        discardChanges: () => {
            const saved = values.defaultReleaseConditions
            actions.setLocalEnabled(saved?.enabled ?? false)
            actions.setLocalGroups(saved?.default_groups ?? [])
        },
    })),

    selectors({
        isEnabled: [(s) => [s.localEnabled], (enabled: boolean): boolean => enabled],

        groups: [
            (s) => [s.localGroups],
            (localGroups: FeatureFlagGroupType[] | null): FeatureFlagGroupType[] => localGroups ?? [],
        ],

        filtersForEditor: [
            (s) => [s.groups],
            (groups: FeatureFlagGroupType[]): FeatureFlagFilters => ({
                groups: groups.length > 0 ? groups : [{ properties: [], rollout_percentage: 0, variant: null }],
                multivariate: null,
                payloads: {},
                aggregation_group_type_index: uniformAggregationGroupTypeIndex(groups),
            }),
        ],

        hasChanges: [
            (s) => [s.localGroups, s.localEnabled, s.defaultReleaseConditions],
            (
                localGroups: FeatureFlagGroupType[] | null,
                localEnabled: boolean,
                saved: DefaultReleaseConditionsResponse | null
            ): boolean => {
                if (!saved) {
                    return false
                }
                return localEnabled !== saved.enabled || !objectsEqual(localGroups, saved.default_groups)
            },
        ],
    }),

    afterMount(({ actions }) => {
        actions.loadDefaultReleaseConditions()
    }),
])