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.

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

import api, { ApiConfig } from 'lib/api'
import { ApiError } from 'lib/api-error'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { identifierToHuman } from 'lib/utils/strings'

import { organizationsProjectsCancelDeletionCreate } from '~/generated/core/api'
import { tagsModel } from '~/models/tagsModel'
import { ProjectType } from '~/types'

import type { OrganizationBasicType } from '../types'
import { organizationLogic } from './organizationLogic'
import { urls } from './urls'
import { userLogic } from './userLogic'

const CREATE_PROJECT_TIMEOUT_MS = 60_000

function toastDuplicateNameConflict(error: string, errorObject: unknown): void {
    const apiError = errorObject as ApiError | undefined
    if (apiError?.status === 409) {
        lemonToast.error(apiError.detail || error)
    }
}

export function isPathOpenWhileProjectPendingDeletion(pathname: string): boolean {
    // projectBased scenes are served under a /project/:id prefix, so match the lockout path by suffix.
    // Tickets load from PostHog's support project, not this one, and reply emails link to them.
    return pathname.endsWith(urls.projectPendingDeletion()) || removeProjectIdIfPresent(pathname) === urls.myTickets()
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectLogicValues {
    currentOrganizationId: string // organizationLogic
    otherOrganizations: OrganizationBasicType[] // userLogic
    currentProject: ProjectType | null
    currentProjectId: number | null
    currentProjectLoading: boolean
    moveProjectDisabledReason: "You can't move the project because you aren't a member of another organization" | null
    projectBeingDeleted: ProjectType | null
    projectBeingMoved: ProjectType | null
    projectBeingMovedLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectLogicActions {
    loadCurrentOrganization: () => any // organizationLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    switchTeam: (
        teamId: number | string,
        destination?: string | undefined
    ) => {
        destination: string | undefined
        teamId: number | string
    } // userLogic
    updateCurrentOrganization: (
        organizationId: string,
        destination?: string | undefined
    ) => {
        destination: string | undefined
        organizationId: string
    } // userLogic
    cancelProjectDeletion: () => any
    cancelProjectDeletionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    cancelProjectDeletionSuccess: (
        currentProject: ProjectType,
        payload?: any
    ) => {
        currentProject: ProjectType
        payload?: any
    }
    createProject: ({ name }: { name: string }) => {
        name: string
    }
    createProjectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createProjectSuccess: (
        currentProject: ProjectType | null,
        payload?: {
            name: string
        }
    ) => {
        currentProject: ProjectType | null
        payload?: {
            name: string
        }
    }
    deleteProject: (project: ProjectType) => {
        project: ProjectType
    }
    deleteProjectFailure: () => {
        value: true
    }
    deleteProjectSuccess: () => {
        value: true
    }
    guardPendingDeletion: (
        pathname: string,
        isPendingDeletion: boolean | null | undefined
    ) => {
        isPendingDeletion: boolean | null | undefined
        pathname: string
    }
    loadCurrentProject: () => any
    loadCurrentProjectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCurrentProjectSuccess: (
        currentProject: ProjectType | null,
        payload?: any
    ) => {
        currentProject: ProjectType | null
        payload?: any
    }
    moveProject: (
        project: ProjectType,
        organizationId: string
    ) => {
        organizationId: string
        project: ProjectType
    }
    moveProjectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    moveProjectSuccess: (
        projectBeingMoved: ProjectType,
        payload?: {
            organizationId: string
            project: ProjectType
        }
    ) => {
        projectBeingMoved: ProjectType
        payload?: {
            organizationId: string
            project: ProjectType
        }
    }
    updateCurrentProject: (payload: Partial<ProjectType>) => Partial<ProjectType>
    updateCurrentProjectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateCurrentProjectSuccess: (
        currentProject: ProjectType,
        payload?: Partial<ProjectType>
    ) => {
        currentProject: ProjectType
        payload?: Partial<ProjectType>
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        currentProjectId: (currentProject: ProjectType | null) => number | null
        moveProjectDisabledReason: (
            otherOrganizations: OrganizationBasicType[]
        ) => "You can't move the project because you aren't a member of another organization" | null
    }
}

export type projectLogicType = MakeLogicType<
    projectLogicValues,
    projectLogicActions,
    Record<string, any>,
    projectLogicMeta
>

export const projectLogic = kea<projectLogicType>([
    path(['scenes', 'projectLogic']),
    actions({
        deleteProject: (project: ProjectType) => ({ project }),
        deleteProjectSuccess: true,
        deleteProjectFailure: true,
        guardPendingDeletion: (pathname: string, isPendingDeletion: boolean | null | undefined) => ({
            pathname,
            isPendingDeletion,
        }),
        moveProject: (project: ProjectType, organizationId: string) => ({ project, organizationId }),
    }),
    connect(() => ({
        actions: [
            userLogic,
            ['loadUser', 'switchTeam', 'updateCurrentOrganization'],
            organizationLogic,
            ['loadCurrentOrganization'],
        ],
        values: [userLogic, ['otherOrganizations'], organizationLogic, ['currentOrganizationId']],
    })),
    reducers({
        projectBeingDeleted: [
            null as ProjectType | null,
            {
                deleteProject: (_, { project }) => project,
                deleteProjectSuccess: () => null,
                deleteProjectFailure: () => null,
            },
        ],
    }),
    loaders(({ values, actions }) => ({
        currentProject: [
            null as ProjectType | null,
            {
                loadCurrentProject: async () => {
                    if (!isUserLoggedIn()) {
                        // If user is anonymous (i.e. viewing a shared dashboard logged out), don't load authenticated stuff
                        return null
                    }
                    try {
                        // @current is the user's server-side current project, which another tab can change.
                        // Once this tab has a project, reload it by id so its API calls stay in it.
                        const projectId = values.currentProject?.id ?? '@current'
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        return await api.get(`api/projects/${projectId}`)
                    } catch {
                        return values.currentProject
                    }
                },
                updateCurrentProject: async (payload: Partial<ProjectType>, breakpoint) => {
                    if (!values.currentProject) {
                        throw new Error('Current project has not been loaded yet, so it cannot be updated!')
                    }

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsPartialUpdate() from '~/generated/core/api' instead.
                    const patchedProject = await api.update<ProjectType>(
                        `api/projects/${values.currentProject.id}`,
                        payload
                    )
                    if ('tags' in payload) {
                        tagsModel.findMounted()?.actions.refreshTags()
                    }
                    breakpoint()

                    // We need to reload current org (which lists its projects) in organizationLogic AND in userLogic
                    actions.loadCurrentOrganization()
                    actions.loadUser()

                    Object.keys(payload).forEach((property) => {
                        posthog.capture(`${property} project setting updated`, {
                            setting: property,
                            value: payload[property],
                        })
                    })

                    if (!window.location.pathname.match(/\/(onboarding|products)/)) {
                        /* Notify user the update was successful  */
                        const updatedAttribute = Object.keys(payload).length === 1 ? Object.keys(payload)[0] : null
                        const message = `${
                            updatedAttribute ? identifierToHuman(updatedAttribute) : 'Project'
                        } updated successfully!`
                        lemonToast.success(message)
                    }

                    return patchedProject
                },
                createProject: async ({ name }: { name: string }) => {
                    // Let failures (e.g. a 403 for non-admins) propagate: kea-loaders surfaces the API
                    // error toast and clears the loading state, and createProjectSuccess never fires — so we
                    // don't switch into a project that wasn't created or leave the modal stuck open.
                    const signal = AbortSignal.timeout(CREATE_PROJECT_TIMEOUT_MS)
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        return await api.create('api/projects/', { name }, { signal })
                    } catch (error) {
                        if (signal.aborted) {
                            actions.loadCurrentOrganization()
                            lemonToast.error(
                                'Creating the project is taking longer than expected. Refresh the page to see if it was created before you try again.'
                            )
                        }
                        throw error
                    }
                },
                cancelProjectDeletion: async () => {
                    if (!values.currentProject) {
                        throw new Error('Current project has not been loaded yet, so it cannot be restored!')
                    }
                    // api/projects/@current returns `organization` instead of `organization_id`, so a reloaded
                    // currentProject has no organization_id and the request would go to /organizations/undefined/
                    return (await organizationsProjectsCancelDeletionCreate(
                        values.currentOrganizationId,
                        values.currentProject.id
                    )) as unknown as ProjectType
                },
            },
        ],

        projectBeingMoved: [
            null as ProjectType | null,
            {
                moveProject: async ({ project, organizationId }) => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsChangeOrganizationCreate() 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.
                    const res = await api.create<ProjectType>(`api/projects/${project.id}/change_organization`, {
                        organization_id: organizationId,
                    })

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersPartialUpdate() from '~/generated/core/api' instead.
                    await api.update('api/users/@me/', { set_current_organization: organizationId })

                    return res
                },
            },
        ],
    })),
    selectors({
        currentProjectId: [
            (s) => [s.currentProject],
            (currentProject: ProjectType | null) => currentProject?.id || null,
        ],
        moveProjectDisabledReason: [
            (s) => [s.otherOrganizations],
            (otherOrganizations: import('~/types').OrganizationBasicType[]) =>
                otherOrganizations.length === 0
                    ? "You can't move the project because you aren't a member of another organization"
                    : null,
        ],
    }),
    listeners(({ actions, values }) => ({
        loadCurrentProjectSuccess: ({ currentProject }) => {
            if (currentProject) {
                ApiConfig.setCurrentProjectId(currentProject.id)
            }
            // Lock the project out once deletion has been initiated (covers full page loads / reloads)
            actions.guardPendingDeletion(router.values.location.pathname, currentProject?.is_pending_deletion)
        },
        locationChanged: ({ pathname }) => {
            actions.guardPendingDeletion(pathname, values.currentProject?.is_pending_deletion)
        },
        updateCurrentProjectFailure: ({ error, errorObject }) => {
            toastDuplicateNameConflict(error, errorObject)
        },
        createProjectFailure: ({ error, errorObject }) => {
            toastDuplicateNameConflict(error, errorObject)
        },
        guardPendingDeletion: ({ pathname, isPendingDeletion }) => {
            const onLockoutScreen = pathname.endsWith(urls.projectPendingDeletion())
            if (isPendingDeletion && !isPathOpenWhileProjectPendingDeletion(pathname)) {
                router.actions.replace(urls.projectPendingDeletion())
            } else if (!isPendingDeletion && onLockoutScreen) {
                // Reached the lockout screen for a project that isn't being deleted (e.g. switched projects) — send home
                router.actions.replace(urls.projectHomepage())
            }
        },
        deleteProject: async ({ project }) => {
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsDestroy() 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.
                await api.delete(`api/projects/${project.id}`)
                actions.deleteProjectSuccess()
            } catch (e) {
                const apiError = e as Record<string, any>
                lemonToast.error(apiError.detail || 'Failed to delete project. Please try again.')
                actions.deleteProjectFailure()
            }
        },
        deleteProjectSuccess: () => {
            lemonToast.success('Project deletion has been scheduled')
            // Full reload so the bootstrap context carries is_pending_deletion and lands on the lockout screen
            window.location.href = urls.projectPendingDeletion()
        },
        cancelProjectDeletionSuccess: () => {
            lemonToast.success('Project deletion has been canceled')
            actions.loadCurrentProject()
        },
        createProjectSuccess: ({ currentProject }) => {
            if (currentProject) {
                actions.switchTeam(currentProject.id)
            }
        },

        moveProjectSuccess: () => {
            lemonToast.success('Project has been moved. Redirecting...')
            window.location.reload()
        },
    })),
    afterMount(({ actions }) => {
        const appContext = getAppContext()
        const currentProject = appContext?.current_project

        if (currentProject) {
            // If app context is available (it should be practically always) we can immediately know currentProject
            actions.loadCurrentProjectSuccess(currentProject)
        } else {
            // If app context is not available, a traditional request is needed
            actions.loadCurrentProject()
        }
    }),
])