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.

8.2 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'

import { matchesSwitcherSearch, newAccountMenuLogic } from 'lib/components/Account/newAccountMenuLogic'
import { pendingInvitesLogic } from 'lib/components/Account/pendingInvitesLogic'
import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { inviteLogic } from 'lib/logic/inviteLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { globalModalsLogic } from '~/layout/globalModalsLogic'
import { AvailableFeature } from '~/types'

import type { GuardAvailableFeatureFn } from '../../lib/components/UpgradeModal/upgradeModalLogic'
import type { OrganizationBasicType, OrganizationType, PendingInviteForCurrentUser, PreflightStatus } from '../../types'

export type OrgMenuActionKey = 'invite-members' | 'billing' | 'org-settings' | 'new-org'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayOrgMenuLogicValues {
    billingEntryUrl: string | null // billingLogic
    currentOrganization: OrganizationType | null // organizationLogic
    pendingInvites: PendingInviteForCurrentUser[] // pendingInvitesLogic
    isCloudOrDev: boolean | undefined // preflightLogic
    preflight: PreflightStatus | null // preflightLogic
    guardAvailableFeature: GuardAvailableFeatureFn // upgradeModalLogic
    isSwitchingOrganization: boolean // userLogic
    otherOrganizations: OrganizationBasicType[] // userLogic
    invites: PendingInviteForCurrentUser[]
    orgMenuActions: OrgMenuActionKey[]
    orgSearchValue: string
    organizations: OrganizationBasicType[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayOrgMenuLogicActions {
    reportInviteMembersButtonClicked: () => {
        value: true
    } // eventUsageLogic
    showCreateOrganizationModal: () => {
        value: true
    } // globalModalsLogic
    showInviteModal: () => {
        value: true
    } // inviteLogic
    closeOrgSwitcher: () => {
        value: true
    } // newAccountMenuLogic
    openOrgSwitcher: () => {
        value: true
    } // newAccountMenuLogic
    updateCurrentOrganization: (
        organizationId: string,
        destination?: string | undefined
    ) => {
        destination: string | undefined
        organizationId: string
    } // userLogic
    openInvite: (inviteId: string) => {
        inviteId: string
    }
    runOrgMenuAction: (key: OrgMenuActionKey) => {
        key: OrgMenuActionKey
    }
    setOrgSearchValue: (searchValue: string) => {
        searchValue: string
    }
    switchOrganization: (organizationId: string) => {
        organizationId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayOrgMenuLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        organizations: (
            currentOrganization: OrganizationType | null,
            otherOrganizations: OrganizationBasicType[],
            orgSearchValue: string
        ) => OrganizationBasicType[]
        invites: (
            pendingInvites: PendingInviteForCurrentUser[],
            orgSearchValue: string
        ) => PendingInviteForCurrentUser[]
        orgMenuActions: (
            isCloudOrDev: boolean | undefined,
            billingEntryUrl: string | null,
            preflight: PreflightStatus | null
        ) => OrgMenuActionKey[]
    }
}

export type todayOrgMenuLogicType = MakeLogicType<
    todayOrgMenuLogicValues,
    todayOrgMenuLogicActions,
    Record<string, any>,
    todayOrgMenuLogicMeta
>

/** The org switcher: the orgs and pending invites the search matches, and the org actions after them. */
export const todayOrgMenuLogic = kea<todayOrgMenuLogicType>([
    path(['layout', 'today', 'todayOrgMenuLogic']),
    connect(() => ({
        values: [
            organizationLogic,
            ['currentOrganization'],
            userLogic,
            ['otherOrganizations', 'isSwitchingOrganization'],
            pendingInvitesLogic,
            ['pendingInvites'],
            preflightLogic,
            ['preflight', 'isCloudOrDev'],
            billingLogic,
            ['billingEntryUrl'],
            upgradeModalLogic,
            ['guardAvailableFeature'],
        ],
        actions: [
            newAccountMenuLogic,
            ['openOrgSwitcher', 'closeOrgSwitcher'],
            userLogic,
            ['updateCurrentOrganization'],
            globalModalsLogic,
            ['showCreateOrganizationModal'],
            inviteLogic,
            ['showInviteModal'],
            eventUsageLogic,
            ['reportInviteMembersButtonClicked'],
        ],
    })),
    actions({
        setOrgSearchValue: (searchValue: string) => ({ searchValue }),
        switchOrganization: (organizationId: string) => ({ organizationId }),
        openInvite: (inviteId: string) => ({ inviteId }),
        runOrgMenuAction: (key: OrgMenuActionKey) => ({ key }),
    }),
    reducers({
        orgSearchValue: [
            '',
            {
                setOrgSearchValue: (_, { searchValue }) => searchValue,
                openOrgSwitcher: () => '',
                closeOrgSwitcher: () => '',
            },
        ],
    }),
    selectors({
        organizations: [
            (s) => [s.currentOrganization, s.otherOrganizations, s.orgSearchValue],
            (
                currentOrganization: OrganizationType | null,
                otherOrganizations: OrganizationBasicType[],
                orgSearchValue: string
            ): OrganizationBasicType[] =>
                [...(currentOrganization ? [currentOrganization] : []), ...otherOrganizations]
                    .filter((organization) => matchesSwitcherSearch(organization.name, orgSearchValue))
                    .sort((a, b) => a.name.localeCompare(b.name)),
        ],
        invites: [
            (s) => [s.pendingInvites, s.orgSearchValue],
            (pendingInvites: PendingInviteForCurrentUser[], orgSearchValue: string): PendingInviteForCurrentUser[] =>
                pendingInvites.filter((invite) => matchesSwitcherSearch(invite.organization_name, orgSearchValue)),
        ],
        orgMenuActions: [
            (s) => [s.isCloudOrDev, s.billingEntryUrl, s.preflight],
            (
                isCloudOrDev: boolean | undefined,
                billingEntryUrl: string | null,
                preflight: PreflightStatus | null
            ): OrgMenuActionKey[] => [
                'invite-members',
                ...(isCloudOrDev && billingEntryUrl ? ['billing' as const] : []),
                'org-settings',
                ...(preflight?.can_create_org ? ['new-org' as const] : []),
            ],
        ],
    }),
    listeners(({ actions, values }) => ({
        switchOrganization: ({ organizationId }) => {
            // A switch reloads the page when it succeeds. Until then, a second pick would race the first.
            if (organizationId === values.currentOrganization?.id || values.isSwitchingOrganization) {
                return
            }
            actions.closeOrgSwitcher()
            actions.updateCurrentOrganization(organizationId)
        },
        openInvite: ({ inviteId }) => {
            window.location.href = urls.inviteSignup(inviteId)
        },
        runOrgMenuAction: ({ key }) => {
            actions.closeOrgSwitcher()
            if (key === 'invite-members') {
                actions.showInviteModal()
                actions.reportInviteMembersButtonClicked()
            } else if (key === 'billing' && values.billingEntryUrl) {
                router.actions.push(values.billingEntryUrl)
            } else if (key === 'org-settings') {
                router.actions.push(urls.settings('organization'))
            } else if (key === 'new-org') {
                values.guardAvailableFeature(
                    AvailableFeature.ORGANIZATIONS_PROJECTS,
                    () => actions.showCreateOrganizationModal(),
                    { guardOnCloud: false }
                )
            }
        },
    })),
])