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.

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

import api, { ApiConfig, ApiError } from 'lib/api'
import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'

import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { AvailableFeature, OrganizationType } from '~/types'

import { urls } from './urls'
import { userLogic } from './userLogic'

/** Mirrors `ALLOWED_WHILE_BLOCKED` in `posthog/middleware.py`. Change one and change the other. */
const ALLOWED_WHILE_BLOCKED: Record<string, string[]> = {
    '/organization-pending-deletion': ['/organization-pending-deletion', '/signup/', '/agentic/authorize'],
    '/organization-deactivated': [
        '/organization-deactivated',
        '/signup/',
        '/agentic/authorize',
        '/organization/billing',
        '/billing/authorization_status',
    ],
}

/**
 * A client-side push reaches no server, so `AutoProjectMiddleware` never resolves the destination's
 * organization. Only a page load can. False while the team list is unknown, which keeps the block on.
 */
function pathLeavesCurrentOrganization(organization: OrganizationType | null, pathname: string): boolean {
    const teams = organization?.teams
    if (!teams) {
        return false
    }
    const projectId = pathname.match(/^\/project\/([^/]+)/)?.[1]
    return projectId !== undefined && !teams.some((team) => String(team.id) === projectId)
}

function organizationBlockPage(organization: OrganizationType | null): string | null {
    if (organization?.is_pending_deletion) {
        return '/organization-pending-deletion'
    }
    if (organization?.is_active === false) {
        return '/organization-deactivated'
    }
    return null
}

export type OrganizationUpdatePayload = Partial<
    Pick<
        OrganizationType,
        | 'name'
        | 'logo_media_id'
        | 'enforce_2fa'
        | 'enforce_verified_domains'
        | 'members_can_invite'
        | 'members_can_create_projects'
        | 'members_can_use_personal_api_keys'
        | 'members_can_see_org_members'
        | 'read_only_mcp_access'
        | 'member_notice'
        | 'is_ai_data_processing_approved'
        | 'is_ai_training_opted_in'
        | 'allow_publicly_shared_resources'
        | 'default_role_id'
        | 'default_anonymize_ips'
    >
>

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface organizationLogicValues {
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
    currentOrganization: OrganizationType | null
    currentOrganizationBlockPage: string | null
    currentOrganizationId: string
    currentOrganizationLoading: boolean
    currentOrganizationProjectCount: number
    isAdminOrOwner: boolean | null
    isCurrentOrganizationNew: boolean
    isCurrentOrganizationUnavailable: boolean
    isNotActiveReason: string | null
    isPathInAnotherOrganization: (pathname: string) => boolean
    isPathOpenWhileBlocked: (pathname: string) => boolean
    migrateAccessControlVersionLoading: boolean
    organizationBeingDeleted: string | null
    projectCreationForbiddenReason: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface organizationLogicActions {
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    completeOnboarding: () => any
    completeOnboardingFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    completeOnboardingSuccess: (
        currentOrganization: OrganizationType | null,
        payload?: any
    ) => {
        currentOrganization: OrganizationType | null
        payload?: any
    }
    createOrganization: (name: string) => string
    createOrganizationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createOrganizationSuccess: (
        currentOrganization: OrganizationType | null,
        payload?: string
    ) => {
        currentOrganization: OrganizationType | null
        payload?: string
    }
    deleteOrganization: ({ organizationId, redirectPath }: { organizationId: string; redirectPath?: string }) => {
        organizationId: string
        redirectPath: string | undefined
    }
    deleteOrganizationFailure: (error: string) => {
        error: string
    }
    deleteOrganizationSuccess: ({ redirectPath }: { redirectPath?: string }) => {
        redirectPath: string | undefined
    }
    loadCurrentOrganization: () => any
    loadCurrentOrganizationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCurrentOrganizationSuccess: (
        currentOrganization: OrganizationType | null,
        payload?: any
    ) => {
        currentOrganization: OrganizationType | null
        payload?: any
    }
    migrateAccessControlVersion: () => any
    migrateAccessControlVersionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    migrateAccessControlVersionSuccess: (
        currentOrganization: OrganizationType | null,
        payload?: any
    ) => {
        currentOrganization: OrganizationType | null
        payload?: any
    }
    updateOrganization: (payload: OrganizationUpdatePayload) => OrganizationUpdatePayload
    updateOrganizationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateOrganizationSuccess: (
        currentOrganization: OrganizationType | null,
        payload?: OrganizationUpdatePayload
    ) => {
        currentOrganization: OrganizationType | null
        payload?: OrganizationUpdatePayload
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface organizationLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        currentOrganizationId: (currentOrganization: OrganizationType | null) => string
        isCurrentOrganizationUnavailable: (
            currentOrganization: OrganizationType | null,
            currentOrganizationLoading: boolean
        ) => boolean
        currentOrganizationProjectCount: (currentOrganization: OrganizationType | null) => number
        projectCreationForbiddenReason: (
            currentOrganization: OrganizationType | null,
            hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
        ) => string | null
        isAdminOrOwner: (currentOrganization: OrganizationType | null) => boolean | null
        isCurrentOrganizationNew: (currentOrganization: OrganizationType | null) => boolean
        isNotActiveReason: (currentOrganization: OrganizationType | null) => string | null
        currentOrganizationBlockPage: (currentOrganization: OrganizationType | null) => string | null
        isPathOpenWhileBlocked: (currentOrganizationBlockPage: string | null) => (pathname: string) => boolean
        isPathInAnotherOrganization: (currentOrganization: OrganizationType | null) => (pathname: string) => boolean
    }
}

export type organizationLogicType = MakeLogicType<
    organizationLogicValues,
    organizationLogicActions,
    Record<string, any>,
    organizationLogicMeta
>

export const organizationLogic = kea<organizationLogicType>([
    path(['scenes', 'organizationLogic']),
    actions({
        deleteOrganization: ({ organizationId, redirectPath }: { organizationId: string; redirectPath?: string }) => ({
            organizationId,
            redirectPath,
        }),
        deleteOrganizationSuccess: ({ redirectPath }: { redirectPath?: string }) => ({ redirectPath }),
        deleteOrganizationFailure: (error: string) => ({ error }),
    }),
    connect(() => ({
        values: [userLogic, ['hasAvailableFeature']],
        actions: [userLogic, ['loadUser']],
    })),
    reducers({
        organizationBeingDeleted: [
            null as string | null,
            {
                deleteOrganization: (_, { organizationId }) => organizationId,
                deleteOrganizationSuccess: () => null,
                deleteOrganizationFailure: () => null,
            },
        ],
        migrateAccessControlVersionLoading: [
            false,
            {
                migrateAccessControlVersion: () => true,
                migrateAccessControlVersionSuccess: () => false,
                migrateAccessControlVersionFailure: () => false,
            },
        ],
    }),
    loaders(({ values }) => ({
        currentOrganization: [
            null as OrganizationType | null,
            {
                loadCurrentOrganization: async () => {
                    if (!isUserLoggedIn()) {
                        // If user is anonymous (i.e. viewing a shared dashboard logged out), don't load authenticated stuff
                        return null
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use retrieve() from 'products/platform_features/frontend/generated/api' instead.
                        return await api.get('api/organizations/@current')
                    } catch (error) {
                        if (error instanceof ApiError && error.status && error.status < 500) {
                            // The organization is gone or out of reach, so let the
                            // unavailable-organization screen take over.
                            return null
                        }
                        // A transient failure keeps the organization we already have. Dropping it leaves
                        // every reader of `currentOrganization.teams` with nothing for the rest of the
                        // session, which is why the project switcher then lists one project.
                        return values.currentOrganization
                    }
                },
                createOrganization: async (name: string) => {
                    await timeSensitiveAuthenticationLogic.findMounted()?.asyncActions.checkReauthentication()
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use create() from 'products/platform_features/frontend/generated/api' instead.
                    return await api.create('api/organizations/', { name })
                },
                updateOrganization: async (payload: OrganizationUpdatePayload) => {
                    if (!values.currentOrganization) {
                        throw new Error('Current organization has not been loaded yet.')
                    }
                    // Check if re-authentication is required, if so, await its completion (or failure)
                    await timeSensitiveAuthenticationLogic.findMounted()?.asyncActions.checkReauthentication()
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use partialUpdate() from 'products/platform_features/frontend/generated/api' instead.
                    const updatedOrganization = await api.update(
                        `api/organizations/${values.currentOrganization.id}`,
                        payload
                    )
                    userLogic.actions.loadUser()
                    return updatedOrganization
                },
                completeOnboarding: async () =>
                    // 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.
                    await api.create(`api/organizations/${values.currentOrganization!.id}/onboarding/`, {}),
                migrateAccessControlVersion: async () => {
                    // 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.
                    await api.create(`api/organizations/${values.currentOrganization!.id}/migrate_access_control/`, {})
                    window.location.reload()
                    return values.currentOrganization // Return current organization state since the page will reload anyway
                },
            },
        ],
    })),
    selectors({
        currentOrganizationId: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): string => {
                if (!currentOrganization || !currentOrganization.id) {
                    // TODO: Fix callers that access currentOrganizationId before the organization is loaded,
                    // then restore the throw. Temporarily falling back to "@current" to avoid crashes.
                    posthog.captureException(new Error('currentOrganizationId accessed before organization loaded'), {
                        severity: 'warning',
                        tag: 'selector_accessed_before_loaded',
                    })
                    return '@current'
                }
                return currentOrganization.id
            },
        ],
        isCurrentOrganizationUnavailable: [
            (s) => [s.currentOrganization, s.currentOrganizationLoading],
            (currentOrganization: OrganizationType | null, currentOrganizationLoading: boolean): boolean =>
                !currentOrganization?.membership_level && !currentOrganizationLoading,
        ],
        // Mirrors PremiumMultiProjectPermission, which counts distinct non-demo projects, not environments
        currentOrganizationProjectCount: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): number =>
                new Set(
                    (currentOrganization?.teams ?? []).filter((team) => !team.is_demo).map((team) => team.project_id)
                ).size,
        ],
        projectCreationForbiddenReason: [
            (s) => [s.currentOrganization, s.hasAvailableFeature],
            (
                currentOrganization: OrganizationType | null,
                hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
            ): string | null => {
                const isAdminOrAbove =
                    !!currentOrganization?.membership_level &&
                    currentOrganization.membership_level >= OrganizationMembershipLevel.Admin
                // Mirror the backend: members can create only when the toggle is on AND the org has the entitlement.
                const membersCanCreate =
                    !!currentOrganization?.members_can_create_projects &&
                    hasAvailableFeature(AvailableFeature.ORGANIZATION_INVITE_SETTINGS)
                if (isAdminOrAbove || membersCanCreate) {
                    return null
                }
                return 'You need to be an organization admin or above to create new projects.'
            },
        ],
        isAdminOrOwner: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): boolean | null =>
                !!(
                    currentOrganization?.membership_level &&
                    [OrganizationMembershipLevel.Admin, OrganizationMembershipLevel.Owner].includes(
                        currentOrganization.membership_level
                    )
                ),
        ],
        isCurrentOrganizationNew: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): boolean => {
                const orgCreatedAt = currentOrganization?.created_at
                return orgCreatedAt ? dayjs().diff(dayjs(orgCreatedAt), 'month') < 3 : false
            },
        ],
        isNotActiveReason: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): string | null =>
                currentOrganization?.is_not_active_reason ?? null,
        ],
        currentOrganizationBlockPage: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): string | null => organizationBlockPage(currentOrganization),
        ],
        isPathOpenWhileBlocked: [
            (s) => [s.currentOrganizationBlockPage],
            (currentOrganizationBlockPage: string | null) =>
                (pathname: string): boolean => {
                    if (currentOrganizationBlockPage === null) {
                        return true
                    }
                    // Compare on the route: the pathname can carry a `/project/<id>` prefix, and the block
                    // page must still count as open with that prefix, or the redirect to it never settles.
                    const route = removeProjectIdIfPresent(pathname)
                    return ALLOWED_WHILE_BLOCKED[currentOrganizationBlockPage].some((allowed) =>
                        route.startsWith(allowed)
                    )
                },
        ],
        isPathInAnotherOrganization: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null) =>
                (pathname: string): boolean =>
                    pathLeavesCurrentOrganization(currentOrganization, pathname),
        ],
    }),
    listeners(({ actions }) => ({
        loadCurrentOrganizationSuccess: ({ currentOrganization }) => {
            if (currentOrganization) {
                ApiConfig.setCurrentOrganizationId(currentOrganization.id)
            }
        },
        createOrganizationSuccess: () => {
            sidePanelStateLogic.findMounted()?.actions.closeSidePanel()
            window.location.href = urls.onboarding()
        },
        updateOrganizationSuccess: () => {
            lemonToast.success('Organization updated successfully!')
        },
        updateOrganizationFailure: ({ error, errorObject }: { error: string; errorObject?: unknown }) => {
            const apiError = errorObject as ApiError | undefined
            lemonToast.error(`Failed to update organization: ${apiError?.detail || error || 'Unknown error'}`)
        },
        deleteOrganization: async ({ organizationId, redirectPath }) => {
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. destroy() 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.delete(`api/organizations/${organizationId}`)
                actions.deleteOrganizationSuccess({ redirectPath })
            } catch (e) {
                const apiError = e as ApiError
                actions.deleteOrganizationFailure(apiError.detail || 'Error deleting organization')
            }
        },
        deleteOrganizationSuccess: ({ redirectPath }) => {
            lemonToast.success('Organization deletion has been initiated', {
                toastId: 'deleteOrganization',
            })

            // When deleting an org as part of the delete-account flow, skip the
            // page reload so the user stays in the modal. The org deletion is
            // async, so a reload would still show the org in the list.
            if (redirectPath === urls.settings('user-danger-zone')) {
                return
            }

            // Reload the page — the middleware will redirect to the pending deletion screen
            location.reload()
        },
        deleteOrganizationFailure: ({ error }) => {
            lemonToast.error(error, {
                toastId: 'deleteOrganization',
            })
        },
    })),
    afterMount(({ actions }) => {
        const appContext = getAppContext()
        const contextualOrganization = appContext?.current_user?.organization
        if (contextualOrganization) {
            // If app context is available (it should be practically always) we can immediately know currentOrganization
            actions.loadCurrentOrganizationSuccess(contextualOrganization)
        } else {
            // If app context is not available, a traditional request is needed
            actions.loadCurrentOrganization()
        }
    }),
])