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.

7.4 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props } from 'kea'
import { loaders } from 'kea-loaders'

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

import api from 'lib/api'
import { ActivityLogItem, userNameForLogItem } from 'lib/components/ActivityLog/humanizeActivity'
import { teamLogic } from 'scenes/teamLogic'

import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { Experiment, FeatureFlagBasicType, FeatureFlagType } from '~/types'

import { featureFlagsActivityRetrieve, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'

import { experimentLogic } from '../experimentLogic'

export interface DeletedFlagBannerLogicProps {
    experimentId: Experiment['id']
    flagId: FeatureFlagBasicType['id']
}

export interface FlagDeletion {
    /** Who deleted the flag, named as the activity log names them. */
    actor: string
    deletedAt: string
    /** The API client that sent the delete, for example `mcp`. */
    client: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface deletedFlagBannerLogicValues {
    currentProjectId: number | string // teamLogic
    deletedFlag: FeatureFlagType | null
    deletedFlagLoading: boolean
    flagDeletion: FlagDeletion | null
    flagDeletionLoading: boolean
    restoredFlag: FeatureFlagType | null
    restoredFlagLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface deletedFlagBannerLogicActions {
    loadExperiment: (
        payload?:
            | {
                  triggeredBy?: import('../experimentLogic').ExperimentTriggeredBy
              }
            | undefined
    ) => {
        triggeredBy?: import('../experimentLogic').ExperimentTriggeredBy
    } // experimentLogic
    loadDeletedFlag: () => any
    loadDeletedFlagFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDeletedFlagSuccess: (
        deletedFlag: FeatureFlagType | null,
        payload?: any
    ) => {
        deletedFlag: FeatureFlagType | null
        payload?: any
    }
    loadFlagDeletion: () => any
    loadFlagDeletionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadFlagDeletionSuccess: (
        flagDeletion: {
            actor: string
            client: string | null
            deletedAt: string
        } | null,
        payload?: any
    ) => {
        flagDeletion: {
            actor: string
            client: string | null
            deletedAt: string
        } | null
        payload?: any
    }
    restoreFlag: () => any
    restoreFlagFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    restoreFlagSuccess: (
        restoredFlag: FeatureFlagType | null,
        payload?: any
    ) => {
        restoredFlag: FeatureFlagType | null
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface deletedFlagBannerLogicMeta {
    key: number
}

export type deletedFlagBannerLogicType = MakeLogicType<
    deletedFlagBannerLogicValues,
    deletedFlagBannerLogicActions,
    DeletedFlagBannerLogicProps,
    deletedFlagBannerLogicMeta
>

export const deletedFlagBannerLogic = kea<deletedFlagBannerLogicType>([
    props({} as DeletedFlagBannerLogicProps),
    key((props) => props.flagId),
    path((key) => ['scenes', 'experiments', 'ExperimentView', 'deletedFlagBannerLogic', key]),
    connect((props: DeletedFlagBannerLogicProps) => ({
        values: [teamLogic, ['currentProjectId']],
        actions: [experimentLogic({ experimentId: props.experimentId }), ['loadExperiment']],
    })),
    loaders(({ props, values }) => ({
        // The experiment's copy of the flag has no `can_edit` and no deleted-cohort marks. The flag API's copy has both.
        deletedFlag: [
            null as FeatureFlagType | null,
            {
                loadDeletedFlag: async () => {
                    try {
                        return (await featureFlagsRetrieve(
                            String(values.currentProjectId),
                            props.flagId
                        )) as unknown as FeatureFlagType
                    } catch {
                        // Without the flag API's copy, the banner offers no restore.
                        return null
                    }
                },
            },
        ],
        flagDeletion: [
            null as FlagDeletion | null,
            {
                loadFlagDeletion: async () => {
                    try {
                        const activity = await featureFlagsActivityRetrieve(
                            String(values.currentProjectId),
                            props.flagId,
                            { limit: 10 }
                        )
                        // The log is newest first, so this is the delete that left the flag deleted.
                        const deletion = activity.results.find((entry) => entry.activity === 'deleted')
                        return deletion
                            ? {
                                  // The generated type leaves `user` untyped. The payload is the one `ActivityLogItem` describes.
                                  actor: userNameForLogItem(deletion as unknown as ActivityLogItem),
                                  deletedAt: deletion.created_at,
                                  client: deletion.client,
                              }
                            : null
                    } catch {
                        // The banner still works without who and when, so a failed read stays quiet.
                        return null
                    }
                },
            },
        ],
        restoredFlag: [
            null as FeatureFlagType | null,
            {
                restoreFlag: async () => {
                    try {
                        // nosemgrep: prefer-codegen-api -- The generated partial update request type has no `deleted` field.
                        const flag: FeatureFlagType = await api.update(
                            `api/projects/${values.currentProjectId}/feature_flags/${props.flagId}`,
                            { deleted: false }
                        )
                        // Restore gives the flag a new tree entry. A delete from another tab or the API leaves the old entry in this tab's tree.
                        deleteFromTree('feature_flag', String(props.flagId))
                        refreshTreeItem('feature_flag', String(props.flagId))
                        // The response carries the restored key, not the one the delete renamed it to.
                        lemonToast.success(`${flag.key} has been restored`)
                        return flag
                    } catch (error: any) {
                        lemonToast.error(error?.detail || "Couldn't restore this feature flag. Try again.")
                        return null
                    }
                },
            },
        ],
    })),
    listeners(({ actions }) => ({
        restoreFlagSuccess: ({ restoredFlag }) => {
            if (restoredFlag) {
                actions.loadExperiment()
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadDeletedFlag()
        actions.loadFlagDeletion()
    }),
])