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.

9.2 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

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

import api from 'lib/api'
import { getApprovalActionLabel, getApprovalResourceUrl } from 'scenes/approvals/utils'
import { Scene } from 'scenes/sceneTypes'
import { rolesLogic } from 'scenes/settings/organization/Permissions/Roles/rolesLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { membersLogic } from '~/models/membersLogic'
import { AvailableFeature, Breadcrumb, ChangeRequest, ChangeRequestState } from '~/types'

export interface ApprovalLogicProps {
    id: string
}

export type ProposedChangesTab = 'gated' | 'full'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface approvalLogicValues {
    currentTeamId: number | null // teamLogic
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    breadcrumbs: Breadcrumb[]
    changeRequest: ChangeRequest | null
    changeRequestLoading: boolean
    changeRequestMissing: boolean
    isApprovalsFeatureEnabled: boolean
    proposedChangesTab: ProposedChangesTab
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface approvalLogicActions {
    loadAllMembers: () => {
        value: true
    } // membersLogic
    loadRoles: () => any // rolesLogic
    approveChangeRequest: (reason?: string) => {
        reason: string | undefined
    }
    cancelChangeRequest: (reason?: string) => {
        reason: string | undefined
    }
    loadChangeRequest: () => {
        value: true
    }
    loadChangeRequestFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadChangeRequestSuccess: (
        changeRequest: ChangeRequest | null,
        payload?: {
            value: true
        }
    ) => {
        changeRequest: ChangeRequest | null
        payload?: {
            value: true
        }
    }
    rejectChangeRequest: (reason: string) => {
        reason: string
    }
    setProposedChangesTab: (tab: ProposedChangesTab) => {
        tab: ProposedChangesTab
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface approvalLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isApprovalsFeatureEnabled: (
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
        ) => boolean
        breadcrumbs: (changeRequest: ChangeRequest | null) => Breadcrumb[]
    }
}

export type approvalLogicType = MakeLogicType<
    approvalLogicValues,
    approvalLogicActions,
    ApprovalLogicProps,
    approvalLogicMeta
>

export const approvalLogic = kea<approvalLogicType>([
    path(['scenes', 'approvals', 'approvalLogic']),
    props({} as ApprovalLogicProps),
    key(({ id }) => id),
    connect(() => ({
        values: [teamLogic, ['currentTeamId'], userLogic, ['hasAvailableFeature']],
        actions: [membersLogic, ['loadAllMembers'], rolesLogic, ['loadRoles']],
    })),
    actions({
        loadChangeRequest: true,
        approveChangeRequest: (reason?: string) => ({ reason }),
        rejectChangeRequest: (reason: string) => ({ reason }),
        cancelChangeRequest: (reason?: string) => ({ reason }),
        setProposedChangesTab: (tab: ProposedChangesTab) => ({ tab }),
    }),
    loaders(({ props, values }) => ({
        changeRequest: [
            null as ChangeRequest | null,
            {
                loadChangeRequest: async () => {
                    if (!values.currentTeamId) {
                        return null
                    }

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use changeRequestsRetrieve() from 'products/platform_features/frontend/generated/api' instead.
                    const response = await api.get<ChangeRequest>(
                        `api/projects/${values.currentTeamId}/change_requests/${props.id}/`
                    )
                    return response
                },
            },
        ],
    })),
    reducers({
        changeRequestMissing: [
            false,
            {
                loadChangeRequestFailure: () => true,
            },
        ],
        proposedChangesTab: [
            'gated' as ProposedChangesTab,
            {
                setProposedChangesTab: (_, { tab }) => tab,
            },
        ],
    }),
    selectors({
        isApprovalsFeatureEnabled: [
            (s) => [s.hasAvailableFeature],
            (hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean): boolean =>
                hasAvailableFeature(AvailableFeature.APPROVALS),
        ],
        breadcrumbs: [
            (s) => [s.changeRequest],
            (changeRequest: ChangeRequest | null): Breadcrumb[] => [
                {
                    key: Scene.Settings,
                    name: 'Approvals',
                    path: urls.approvals(),
                },
                {
                    key: Scene.Approval,
                    name: changeRequest ? getApprovalActionLabel(changeRequest.action_key) : 'Loading...',
                },
            ],
        ],
    }),
    listeners(({ actions, values, props }) => {
        const navigateAfterAction = (fullReload: boolean = false): void => {
            const cr = values.changeRequest
            const resourceUrl = cr ? getApprovalResourceUrl(cr.resource_type, cr.resource_id) : null
            const targetUrl = resourceUrl || urls.approvals()

            if (fullReload) {
                window.location.href = targetUrl
            } else {
                router.actions.push(targetUrl)
            }
        }

        return {
            approveChangeRequest: async ({ reason }) => {
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use changeRequestsApproveCreate() from 'products/platform_features/frontend/generated/api' instead.
                    const response = await api.create(
                        `api/projects/${values.currentTeamId}/change_requests/${props.id}/approve/`,
                        { reason: reason || '' }
                    )

                    if (response.status === ChangeRequestState.Applied) {
                        lemonToast.success('Change request approved and applied successfully')
                        setTimeout(() => navigateAfterAction(true), 2000)
                    } else if (response.status === ChangeRequestState.Failed) {
                        lemonToast.error(`Approval succeeded but application failed: ${response.message}`)
                        actions.loadChangeRequest()
                    } else {
                        lemonToast.success(response.message || 'Change request approved')
                        actions.loadChangeRequest()
                    }
                } catch (error: any) {
                    lemonToast.error(error.detail || 'Failed to approve change request')
                }
            },
            rejectChangeRequest: async ({ reason }) => {
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use changeRequestsRejectCreate() from 'products/platform_features/frontend/generated/api' instead.
                    await api.create(`api/projects/${values.currentTeamId}/change_requests/${props.id}/reject/`, {
                        reason,
                    })
                    lemonToast.success('Change request rejected')
                    navigateAfterAction()
                } catch (error: any) {
                    lemonToast.error(error.detail || 'Failed to reject change request')
                }
            },
            cancelChangeRequest: async ({ reason }) => {
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. changeRequestsCancelCreate() from 'products/platform_features/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                    await api.create(`api/projects/${values.currentTeamId}/change_requests/${props.id}/cancel/`, {
                        reason,
                    })
                    lemonToast.success('Change request canceled')
                    navigateAfterAction()
                } catch (error: any) {
                    lemonToast.error(error.detail || 'Failed to cancel change request')
                }
            },
        }
    }),
    urlToAction(({ actions, props }) => ({
        [urls.approval(props.id ?? ':id')]: () => {
            actions.loadChangeRequest()
        },
    })),
    afterMount(({ actions }) => {
        actions.loadChangeRequest()
        actions.loadAllMembers()
        actions.loadRoles()
    }),
])