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.5 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { lazyLoaders, loaders } from 'kea-loaders'

import api, { PaginatedResponse } from 'lib/api'
import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { bindModalToUrl } from 'lib/logic/bindModalToUrl'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { pluralize } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'

import { membersLogic } from '~/models/membersLogic'
import { AccessControlLevel, OrganizationInviteType, OrganizationMemberType, PreflightStatus, UserType } from '~/types'

/** State of a single invite row (with input data) in bulk invite creation. */
export interface InviteRowState {
    target_email: string
    first_name: string
    level: OrganizationMembershipLevel
    isValid: boolean
    message?: string
    private_project_access: Array<{ id: number; level: AccessControlLevel.Member | AccessControlLevel.Admin }>
}

export interface InviteFieldError {
    attr: string
    detail: string
}

// The bulk endpoint collapses per-row errors to the first one, so a row field can't be pinned to its row.
const INLINE_ERROR_FIELDS = new Set(['message', 'first_name'])

const EMPTY_INVITE: InviteRowState = {
    target_email: '',
    first_name: '',
    level: OrganizationMembershipLevel.Member,
    isValid: true,
    private_project_access: [],
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inviteLogicValues {
    members: OrganizationMemberType[] | null // membersLogic
    preflight: PreflightStatus | null // preflightLogic
    user: UserType | null // userLogic
    availableProjects: any[]
    canSubmit: boolean
    existingMemberEmails: Set<string>
    existingMemberInviteRows: boolean[]
    hasExistingMemberInvite: boolean
    inviteContainsOwnerLevel: boolean
    inviteFieldError: InviteFieldError | null
    invitedTeamMembersInternal: OrganizationInviteType[]
    invitedTeamMembersInternalLoading: boolean
    invites: OrganizationInviteType[]
    invitesLoading: boolean
    invitesToSend: InviteRowState[]
    isInviteConfirmed: boolean
    isInviteModalShown: boolean
    isInviting: boolean
    message: string
    messageError: string | null
    projectAccessControls: Record<
        number,
        {
            access_level: string
        }
    >
    projectAccessControlsLoading: boolean
    recipientNameError: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inviteLogicActions {
    ensureAllMembersLoaded: () => {
        value: true
    } // membersLogic
    loadAllMembers: () => {
        value: true
    } // membersLogic
    addProjectAccess: (
        inviteIndex: number,
        projectId: number,
        level: AccessControlLevel
    ) => {
        inviteIndex: number
        level: AccessControlLevel
        projectId: number
    }
    appendInviteRow: () => {
        value: true
    }
    deleteInvite: (invite: OrganizationInviteType) => OrganizationInviteType
    deleteInviteAtIndex: (index: number) => {
        index: number
    }
    deleteInviteFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteInviteSuccess: (
        invites: OrganizationInviteType[],
        payload?: OrganizationInviteType
    ) => {
        invites: OrganizationInviteType[]
        payload?: OrganizationInviteType
    }
    hideInviteModal: () => {
        value: true
    }
    inviteTeamMembers: () => any
    inviteTeamMembersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    inviteTeamMembersSuccess: (
        invitedTeamMembersInternal: OrganizationInviteType[],
        payload?: any
    ) => {
        invitedTeamMembersInternal: OrganizationInviteType[]
        payload?: any
    }
    loadInvites: () => any
    loadInvitesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInvitesSuccess: (
        invites: OrganizationInviteType[],
        payload?: any
    ) => {
        invites: OrganizationInviteType[]
        payload?: any
    }
    loadProjectAccessControl: (projectId: number) => number
    loadProjectAccessControlFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadProjectAccessControlSuccess: (
        projectAccessControls: {
            [x: number]: any
        },
        payload?: number
    ) => {
        projectAccessControls: {
            [x: number]: any
        }
        payload?: number
    }
    removeProjectAccess: (
        inviteIndex: number,
        projectId: number
    ) => {
        inviteIndex: number
        projectId: number
    }
    resetInviteRows: () => {
        value: true
    }
    setIsInviteConfirmed: (inviteConfirmed: boolean) => {
        inviteConfirmed: boolean
    }
    showInviteModal: () => {
        value: true
    }
    updateInviteAtIndex: (
        payload: any,
        index: number
    ) => {
        index: number
        payload: any
    }
    updateMessage: (message: string) => {
        message: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inviteLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        inviteContainsOwnerLevel: (invitesToSend: InviteRowState[]) => boolean
        existingMemberEmails: (user: UserType | null, members: OrganizationMemberType[] | null) => Set<string>
        existingMemberInviteRows: (invitesToSend: InviteRowState[], existingMemberEmails: Set<string>) => boolean[]
        hasExistingMemberInvite: (existingMemberInviteRows: boolean[]) => boolean
        canSubmit: (
            invitesToSend: InviteRowState[],
            inviteContainsOwnerLevel: boolean,
            isInviteConfirmed: boolean,
            hasExistingMemberInvite: boolean
        ) => boolean
        availableProjects: (currentOrganization: null | import('~/types').OrganizationType) => any[]
        isInviting: (invitedTeamMembersInternalLoading: boolean) => boolean
        messageError: (inviteFieldError: InviteFieldError | null) => string | null
        recipientNameError: (inviteFieldError: InviteFieldError | null) => string | null
    }
}

export type inviteLogicType = MakeLogicType<inviteLogicValues, inviteLogicActions, Record<string, any>, inviteLogicMeta>

export const inviteLogic = kea<inviteLogicType>([
    path(['lib', 'logic', 'inviteLogic']),
    connect(() => ({
        values: [preflightLogic, ['preflight'], userLogic, ['user'], membersLogic, ['members']],
        actions: [membersLogic, ['ensureAllMembersLoaded', 'loadAllMembers']],
    })),
    actions({
        showInviteModal: true,
        hideInviteModal: true,
        updateInviteAtIndex: (payload, index: number) => ({ payload, index }),
        deleteInviteAtIndex: (index: number) => ({ index }),
        updateMessage: (message: string) => ({ message }),
        appendInviteRow: true,
        resetInviteRows: true,
        setIsInviteConfirmed: (inviteConfirmed: boolean) => ({ inviteConfirmed }),
        addProjectAccess: (inviteIndex: number, projectId: number, level: AccessControlLevel) => ({
            inviteIndex,
            projectId,
            level,
        }),
        removeProjectAccess: (inviteIndex: number, projectId: number) => ({ inviteIndex, projectId }),
    }),
    loaders(({ values }) => ({
        invitedTeamMembersInternal: [
            [] as OrganizationInviteType[],
            {
                inviteTeamMembers: async () => {
                    // A sent request always returns at least one invite, so the success handlers
                    // treat this empty result as "nothing was sent" and keep the form as it is.
                    if (!values.canSubmit) {
                        return []
                    }

                    const payload: Pick<
                        OrganizationInviteType,
                        'target_email' | 'first_name' | 'level' | 'message' | 'private_project_access'
                    >[] = values.invitesToSend.filter((invite) => invite.target_email)
                    if (values.message) {
                        payload.forEach((payload) => (payload.message = values.message))
                    }
                    // Inviting members is a sensitive action; if re-authentication is required,
                    // await its completion so the invite resumes once the user re-authenticates.
                    await timeSensitiveAuthenticationLogic.findMounted()?.asyncActions.checkReauthentication()
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. invitesBulkCreate() 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.
                    return await api.create<OrganizationInviteType[]>(
                        `api/organizations/${organizationLogic.values.currentOrganizationId}/invites/bulk/`,
                        payload
                    )
                },
            },
        ],
        projectAccessControls: [
            {} as Record<number, { access_level: string }>,
            {
                loadProjectAccessControl: async (projectId: number) => {
                    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.
                        const accessControls = await api.get(`api/projects/${projectId}/access_controls`)
                        // Look for project-level access control (resource: "project", organization_member: null, role: null)
                        const projectAccessControl = accessControls.access_controls?.find(
                            (control: any) =>
                                control.resource === 'project' &&
                                control.organization_member === null &&
                                control.role === null
                        )
                        return {
                            ...values.projectAccessControls,
                            [projectId]: projectAccessControl || { access_level: accessControls.default_access_level },
                        }
                    } catch {
                        return values.projectAccessControls
                    }
                },
            },
        ],
    })),
    lazyLoaders(({ values }) => ({
        invites: [
            [] as OrganizationInviteType[],
            {
                loadInvites: async () => {
                    return organizationLogic.values.currentOrganization
                        ? (
                              await api.get<PaginatedResponse<OrganizationInviteType>>( // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                                  `api/organizations/${organizationLogic.values.currentOrganizationId}/invites/`
                              )
                          ).results
                        : []
                },
                deleteInvite: async (invite: OrganizationInviteType) => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. invitesDestroy() 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/organizations/${organizationLogic.values.currentOrganizationId}/invites/${invite.id}/`
                    )
                    preflightLogic.actions.loadPreflight() // Make sure licensed_users_available is updated
                    lemonToast.success(`Invite for ${invite.target_email} has been canceled`)
                    return values.invites.filter((thisInvite) => thisInvite.id !== invite.id)
                },
            },
        ],
    })),
    reducers(() => ({
        isInviteModalShown: [
            false,
            {
                showInviteModal: () => true,
                hideInviteModal: () => false,
            },
        ],
        invitesToSend: [
            [EMPTY_INVITE] as InviteRowState[],
            {
                updateInviteAtIndex: (state, { payload, index }) => {
                    const newState = [...state]
                    newState[index] = { ...state[index], ...payload }
                    return newState
                },
                deleteInviteAtIndex: (state, { index }) => {
                    const newState = [...state]
                    newState.splice(index, 1)
                    return newState
                },
                appendInviteRow: (state) => [...state, EMPTY_INVITE],
                resetInviteRows: () => [EMPTY_INVITE],
                inviteTeamMembersSuccess: (state, { invitedTeamMembersInternal }) =>
                    invitedTeamMembersInternal.length > 0 ? [EMPTY_INVITE] : state,
                addProjectAccess: (state, { inviteIndex, projectId, level }) => {
                    const newState = [...state]
                    const invite = { ...newState[inviteIndex] }

                    // Remove existing access for this project if it exists
                    invite.private_project_access = invite.private_project_access.filter(
                        (access) => access.id !== projectId
                    )

                    // Add new access
                    invite.private_project_access.push({
                        id: projectId,
                        level: level as AccessControlLevel.Member | AccessControlLevel.Admin,
                    })
                    newState[inviteIndex] = invite
                    return newState
                },
                removeProjectAccess: (state, { inviteIndex, projectId }) => {
                    const newState = [...state]
                    const invite = { ...newState[inviteIndex] }
                    invite.private_project_access = invite.private_project_access.filter(
                        (access) => access.id !== projectId
                    )
                    newState[inviteIndex] = invite
                    return newState
                },
            },
        ],
        message: [
            '',
            {
                updateMessage: (_, { message }) => message,
            },
        ],
        isInviteConfirmed: [
            false,
            {
                setIsInviteConfirmed: (_, { inviteConfirmed }) => inviteConfirmed,
            },
        ],
        inviteFieldError: [
            null as InviteFieldError | null,
            {
                inviteTeamMembersFailure: (_, { errorObject }) =>
                    INLINE_ERROR_FIELDS.has(errorObject?.attr) && errorObject?.detail
                        ? { attr: errorObject.attr, detail: errorObject.detail }
                        : null,
                inviteTeamMembersSuccess: (state, { invitedTeamMembersInternal }) =>
                    invitedTeamMembersInternal.length > 0 ? null : state,
                updateMessage: (state) => (state?.attr === 'message' ? null : state),
                updateInviteAtIndex: (state, { payload }) =>
                    state?.attr === 'first_name' && 'first_name' in payload ? null : state,
                deleteInviteAtIndex: (state) => (state?.attr === 'first_name' ? null : state),
                hideInviteModal: () => null,
            },
        ],
    })),
    selectors({
        inviteContainsOwnerLevel: [
            (selectors) => [selectors.invitesToSend],
            (invites: InviteRowState[]) => {
                return invites.filter(({ level }) => level === OrganizationMembershipLevel.Owner).length > 0
            },
        ],
        existingMemberEmails: [
            (selectors) => [selectors.user, selectors.members],
            (user: UserType | null, members: OrganizationMemberType[] | null): Set<string> => {
                // The user's own email counts before the member list loads.
                const emails = [user?.email, ...(members ?? []).map((member) => member.user?.email)]
                return new Set(emails.filter((email): email is string => !!email).map((email) => email.toLowerCase()))
            },
        ],
        existingMemberInviteRows: [
            (selectors) => [selectors.invitesToSend, selectors.existingMemberEmails],
            (invites: InviteRowState[], existingMemberEmails: Set<string>): boolean[] =>
                invites.map(({ target_email }) => existingMemberEmails.has(target_email.trim().toLowerCase())),
        ],
        hasExistingMemberInvite: [
            (selectors) => [selectors.existingMemberInviteRows],
            (existingMemberInviteRows: boolean[]): boolean => existingMemberInviteRows.some(Boolean),
        ],
        canSubmit: [
            (selectors) => [
                selectors.invitesToSend,
                selectors.inviteContainsOwnerLevel,
                selectors.isInviteConfirmed,
                selectors.hasExistingMemberInvite,
            ],
            (
                invites: InviteRowState[],
                inviteContainsOwnerLevel: boolean,
                isInviteConfirmed: boolean,
                hasExistingMemberInvite: boolean
            ) => {
                const ownerLevelConfirmed = inviteContainsOwnerLevel ? isInviteConfirmed : true
                return (
                    invites.filter(({ target_email }) => !!target_email).length > 0 &&
                    invites.filter(({ isValid }) => !isValid).length == 0 &&
                    !hasExistingMemberInvite &&
                    ownerLevelConfirmed
                )
            },
        ],
        availableProjects: [
            () => [organizationLogic.selectors.currentOrganization],
            (currentOrganization: any) => {
                return [...(currentOrganization?.teams || [])].sort((a, b) => a.name.localeCompare(b.name))
            },
        ],
        isInviting: [
            (selectors) => [selectors.invitedTeamMembersInternalLoading],
            (invitedTeamMembersInternalLoading: boolean) => invitedTeamMembersInternalLoading,
        ],
        messageError: [
            (selectors) => [selectors.inviteFieldError],
            (inviteFieldError: InviteFieldError | null): string | null =>
                inviteFieldError?.attr === 'message' ? inviteFieldError.detail : null,
        ],
        recipientNameError: [
            (selectors) => [selectors.inviteFieldError],
            (inviteFieldError: InviteFieldError | null): string | null =>
                inviteFieldError?.attr === 'first_name' ? inviteFieldError.detail : null,
        ],
    }),
    listeners(({ values, actions }) => ({
        inviteTeamMembersSuccess: ({ invitedTeamMembersInternal }): void => {
            if (invitedTeamMembersInternal.length === 0) {
                return
            }
            const inviteCount = invitedTeamMembersInternal.length
            if (values.preflight?.email_service_available) {
                lemonToast.success(`Invited ${pluralize(inviteCount, 'new team member')}`)
            } else {
                lemonToast.success('Team invite links generated')
            }

            organizationLogic.actions.loadCurrentOrganization()
            actions.loadInvites()

            if (values.preflight?.email_service_available) {
                actions.hideInviteModal()
            }
        },
        inviteTeamMembersFailure: ({ errorObject }) => {
            // Someone joined after the member list loaded. Reload it so the row shows the error.
            if (errorObject?.code === 'existing_member') {
                actions.loadAllMembers()
            }
        },
        addProjectAccess: ({ projectId }) => {
            // Load access control for the project when it's added
            actions.loadProjectAccessControl(projectId)
        },
    })),
    bindModalToUrl({
        urlKey: 'invite-members',
        openActionKey: 'showInviteModal',
        closeActionKey: 'hideInviteModal',
        isOpenKey: 'isInviteModalShown',
    }),
])