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.

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

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

import api from 'lib/api'
import { toParams } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

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

import type { ApprovalContext, ChangeRequestCreatedEventDetail } from './utils'

export interface ChangeRequestsLogicProps {
    resourceType: string
    resourceId: string | number
    actionKey?: string
    /** Display context — controls banner wording (e.g. "experiment" instead of "feature flag") */
    context?: ApprovalContext
}

export interface ChangeRequestButtonVisibility {
    showApproveButton: boolean
    showRejectButton: boolean
    showCancelButton: boolean
}

export function getChangeRequestButtonVisibility(changeRequest: ChangeRequest): ChangeRequestButtonVisibility {
    const isPending = changeRequest.state === ChangeRequestState.Pending
    const canApprove = changeRequest.can_approve
    const canCancel = changeRequest.can_cancel
    const isRequester = changeRequest.is_requester
    const hasVoted = !!changeRequest.user_decision

    return {
        showApproveButton: isPending && canApprove && !hasVoted,
        showRejectButton: isPending && canApprove && !isRequester && !hasVoted,
        showCancelButton: isPending && isRequester && canCancel,
    }
}

/**
 * Reason the Approve button is disabled for the current user, or null when they can approve.
 * Only meaningful while the request is pending — callers gate on that before rendering the button.
 */
export function getApproveDisabledReason(changeRequest: ChangeRequest): string | null {
    if (changeRequest.state !== ChangeRequestState.Pending) {
        return null
    }
    if (changeRequest.user_decision) {
        return "You've already voted on this change request."
    }
    if (changeRequest.is_requester && !changeRequest.policy_snapshot?.allow_self_approve) {
        return "You can't approve a change request you created."
    }
    if (!changeRequest.can_approve) {
        return "You don't have permission to approve this change request, based on your organization's approval policies."
    }
    return null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface changeRequestsLogicValues {
    currentTeamId: number | null // teamLogic
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    buttonVisibility: ChangeRequestButtonVisibility | null
    changeRequests: ChangeRequest[]
    changeRequestsLoading: boolean
    pendingChangeRequest: ChangeRequest | null
    shouldShowBanner: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface changeRequestsLogicActions {
    approveRequest: (id: string) => {
        id: string
    }
    cancelRequest: (
        id: string,
        reason?: string
    ) => {
        id: string
        reason: string | undefined
    }
    loadChangeRequests: () => {
        value: true
    }
    loadChangeRequestsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadChangeRequestsSuccess: (
        changeRequests: ChangeRequest[],
        payload?: {
            value: true
        }
    ) => {
        changeRequests: ChangeRequest[]
        payload?: {
            value: true
        }
    }
    rejectRequest: (
        id: string,
        reason?: string
    ) => {
        id: string
        reason: string | undefined
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface changeRequestsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        pendingChangeRequest: (changeRequests: ChangeRequest[]) => ChangeRequest | null
        shouldShowBanner: (pendingChangeRequest: ChangeRequest | null) => boolean
        buttonVisibility: (pendingChangeRequest: ChangeRequest | null) => ChangeRequestButtonVisibility | null
    }
}

export type changeRequestsLogicType = MakeLogicType<
    changeRequestsLogicValues,
    changeRequestsLogicActions,
    ChangeRequestsLogicProps,
    changeRequestsLogicMeta
>

export const changeRequestsLogic = kea<changeRequestsLogicType>([
    path(['scenes', 'approvals', 'changeRequestsLogic']),
    props({} as ChangeRequestsLogicProps),
    key((props) => `${props.resourceType}-${props.resourceId}`),

    connect(() => ({
        values: [teamLogic, ['currentTeamId'], userLogic, ['hasAvailableFeature']],
    })),

    actions({
        loadChangeRequests: true,
        approveRequest: (id: string) => ({ id }),
        rejectRequest: (id: string, reason?: string) => ({ id, reason }),
        cancelRequest: (id: string, reason?: string) => ({ id, reason }),
    }),

    loaders(({ props, values }) => ({
        changeRequests: [
            [] as ChangeRequest[],
            {
                loadChangeRequests: async () => {
                    if (!values.currentTeamId || !values.hasAvailableFeature(AvailableFeature.APPROVALS)) {
                        return []
                    }

                    const params: Record<string, string> = {
                        resource_type: props.resourceType,
                        resource_id: String(props.resourceId),
                        state: 'pending,approved',
                    }

                    if (props.actionKey) {
                        params.action_key = props.actionKey
                    }

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use changeRequestsList() from 'products/platform_features/frontend/generated/api' instead.
                    const response = await api.get(
                        `api/projects/${values.currentTeamId}/change_requests?${toParams(params)}`
                    )
                    return response.results || []
                },
            },
        ],
    })),

    selectors({
        pendingChangeRequest: [
            (s) => [s.changeRequests],
            (changeRequests: ChangeRequest[]): ChangeRequest | null => {
                const pending = changeRequests.filter(
                    (cr) => cr.state === ChangeRequestState.Pending || cr.state === ChangeRequestState.Approved
                )
                return pending.length > 0 ? pending[0] : null
            },
        ],

        shouldShowBanner: [
            (s) => [s.pendingChangeRequest],
            (pendingChangeRequest: ChangeRequest | null): boolean => {
                return pendingChangeRequest !== null
            },
        ],

        buttonVisibility: [
            (s) => [s.pendingChangeRequest],
            (pendingChangeRequest: ChangeRequest | null): ChangeRequestButtonVisibility | null => {
                if (!pendingChangeRequest) {
                    return null
                }
                return getChangeRequestButtonVisibility(pendingChangeRequest)
            },
        ],
    }),

    listeners(({ actions, values }) => ({
        approveRequest: async ({ id }) => {
            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/${id}/approve/`,
                    {}
                )

                if (response.status === ChangeRequestState.Applied) {
                    lemonToast.success('Change request approved and applied successfully')

                    setTimeout(() => {
                        window.location.reload()
                    }, 2000)
                } else if (response.status === ChangeRequestState.Failed) {
                    lemonToast.error(`Approval succeeded but application failed: ${response.message}`)
                    actions.loadChangeRequests()
                } else {
                    lemonToast.success(response.message || 'Change request approved')
                    actions.loadChangeRequests()
                }
            } catch (error: any) {
                lemonToast.error(error.detail || 'Failed to approve change request')
            }
        },

        rejectRequest: async ({ id, 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/${id}/reject/`, { reason })
                lemonToast.success('Change request rejected')
                actions.loadChangeRequestsSuccess(values.changeRequests.filter((cr) => cr.id !== id))
            } catch (error: any) {
                lemonToast.error(error.detail || 'Failed to reject change request')
            }
        },

        cancelRequest: async ({ id, 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/${id}/cancel/`, { reason })
                lemonToast.success('Change request canceled')
                // Optimistically remove the canceled CR so the banner disappears immediately
                actions.loadChangeRequestsSuccess(values.changeRequests.filter((cr) => cr.id !== id))
            } catch (error: any) {
                lemonToast.error(error.detail || 'Failed to cancel change request')
            }
        },
    })),

    afterMount(({ actions, props }) => {
        actions.loadChangeRequests()

        const handleChangeRequestCreated = (event: CustomEvent<ChangeRequestCreatedEventDetail>): void => {
            const { resourceType, resourceId } = event.detail
            if (resourceType === props.resourceType && String(resourceId) === String(props.resourceId)) {
                actions.loadChangeRequests()
            }
        }

        window.addEventListener('change-request-created', handleChangeRequestCreated as EventListener)

        return () => {
            window.removeEventListener('change-request-created', handleChangeRequestCreated as EventListener)
        }
    }),
])