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.

43.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'

import api, { ApiConfig, getCookie } from 'lib/api'
import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic'
// eslint-disable-next-line import/no-cycle
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getAppContext } from 'lib/utils/getAppContext'
import { clearSession, isOAuthMode, setOAuthContextIds } from 'lib/utils/oauthClient'
import { identifyUserInPostHog } from 'lib/utils/posthogIdentity'
import { clearPendingVerificationEmail } from 'scenes/authentication/shared/verificationCode'

import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { AvailableFeature, NotificationSettings, OrganizationBasicType, UserRole, UserTheme, UserType } from '~/types'

import {
    clearSQLEditorDraftFromStorageEvent,
    clearSQLEditorDrafts,
} from 'products/data_warehouse/frontend/sqlEditorDraftCleanup'

import type { BillingFeatureType } from '../types'
import { urls } from './urls'

export interface UserDetailsFormType {
    first_name: string
    email: string
}

type DigestProjectSettingKey =
    | 'error_tracking_weekly_digest_project_enabled'
    | 'web_analytics_weekly_digest_project_enabled'

function updateDigestProjectSetting(
    key: DigestProjectSettingKey,
    teamId: number,
    enabled: boolean,
    values: { user: UserType | null },
    actions: { updateUser: (user: Partial<UserType>) => void }
): void {
    if (!values.user?.notification_settings) {
        return
    }
    actions.updateUser({
        notification_settings: {
            ...values.user.notification_settings,
            [key]: { ...values.user.notification_settings[key], [teamId]: enabled },
        },
    })
}

function updateDigestProjectSettings(
    key: DigestProjectSettingKey,
    teamIds: number[],
    enabled: boolean,
    values: { user: UserType | null },
    actions: { updateUser: (user: Partial<UserType>) => void }
): void {
    if (!values.user?.notification_settings) {
        return
    }
    const projectSettings: Record<string, boolean> = { ...values.user.notification_settings[key] }
    teamIds?.forEach((teamId) => {
        projectSettings[teamId] = enabled
    })
    actions.updateUser({
        notification_settings: { ...values.user.notification_settings, [key]: projectSettings } as NotificationSettings,
    })
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface userLogicValues {
    availableFeature: (feature: AvailableFeature) => BillingFeatureType | null | undefined
    credentialReviewDismissedInSession: boolean
    hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
    isImpersonationUpgradeInProgress: boolean
    isProvisionedUser: boolean
    isSwitchingOrganization: boolean
    isUserDetailsSubmitting: boolean
    isUserDetailsValid: boolean
    isUserNonTechnical: boolean
    optimisticThemeMode: UserTheme | null
    otherOrganizations: OrganizationBasicType[]
    showUserDetailsErrors: boolean
    themeMode: UserTheme
    user: UserType | null
    userDetails: UserDetailsFormType
    userDetailsAllErrors: Record<string, any>
    userDetailsChanged: boolean
    userDetailsErrors: DeepPartialMap<Record<string, any>, ValidationErrorType>
    userDetailsHasErrors: boolean
    userDetailsManualErrors: Record<string, any>
    userDetailsTouched: boolean
    userDetailsTouches: Record<string, boolean>
    userDetailsValidationErrors: DeepPartialMap<Record<string, any>, ValidationErrorType>
    userLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface userLogicActions {
    addFullStageUserFields: (fields: Partial<UserType>) => {
        fields: Partial<UserType>
    }
    addFullStageUserFieldsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    addFullStageUserFieldsSuccess: (
        user: UserType | null,
        payload?: {
            fields: Partial<UserType>
        }
    ) => {
        user: UserType | null
        payload?: {
            fields: Partial<UserType>
        }
    }
    cancelEmailChangeRequest: () => {
        value: true
    }
    cancelEmailChangeRequestFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    cancelEmailChangeRequestSuccess: (
        user: UserType,
        payload?: {
            value: true
        }
    ) => {
        user: UserType
        payload?: {
            value: true
        }
    }
    credentialReviewDismissed: () => {
        value: true
    }
    deleteUser: () => {
        value: true
    }
    deleteUserFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteUserSuccess: (
        user: UserType | null,
        payload?: {
            value: true
        }
    ) => {
        user: UserType | null
        payload?: {
            value: true
        }
    }
    loadUser: (resetOnFailure?: boolean) => {
        resetOnFailure: boolean | undefined
    }
    loadUserFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadUserSuccess: (
        user: UserType | null,
        payload?: {
            resetOnFailure: boolean | undefined
        }
    ) => {
        user: UserType | null
        payload?: {
            resetOnFailure: boolean | undefined
        }
    }
    logout: (
        preserveLocation?: any,
        nextUrl?: string,
        reason?: string
    ) => {
        nextUrl: string | undefined
        preserveLocation: any
        reason: string | undefined
    }
    resetUserDetails: (values?: Record<string, any>) => {
        values?: Record<string, any>
    }
    setUserDetailsManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setUserDetailsValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setUserDetailsValues: (values: DeepPartial<Record<string, any>>) => {
        values: DeepPartial<Record<string, any>>
    }
    setUserScenePersonalisation: (
        scene: DashboardCompatibleScenes,
        dashboard: number
    ) => {
        dashboard: number
        scene: DashboardCompatibleScenes
    }
    setUserScenePersonalisationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    setUserScenePersonalisationSuccess: (
        user: UserType,
        payload?: {
            dashboard: number
            scene: DashboardCompatibleScenes
        }
    ) => {
        user: UserType
        payload?: {
            dashboard: number
            scene: DashboardCompatibleScenes
        }
    }
    submitUserDetails: () => {
        value: boolean
    }
    submitUserDetailsFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitUserDetailsRequest: (userDetails: Record<string, any>) => {
        userDetails: Record<string, any>
    }
    submitUserDetailsSuccess: (userDetails: Record<string, any>) => {
        userDetails: Record<string, any>
    }
    switchTeam: (
        teamId: number | string,
        destination?: string
    ) => {
        destination: string | undefined
        teamId: number | string
    }
    touchUserDetailsField: (key: string) => {
        key: string
    }
    updateAllRealtimeNotifications: (
        teamIds: number[],
        types: string[],
        enabled: boolean
    ) => {
        enabled: boolean
        teamIds: number[]
        types: string[]
    }
    updateCurrentOrganization: (
        organizationId: string,
        destination?: string
    ) => {
        destination: string | undefined
        organizationId: string
    }
    updateCurrentOrganizationFailure: () => {
        value: true
    }
    updateDataPipelineErrorThreshold: (threshold: number) => {
        threshold: number
    }
    updateETWeeklyDigestForAllTeams: (
        teamIds: number[],
        enabled: boolean
    ) => {
        enabled: boolean
        teamIds: number[]
    }
    updateETWeeklyDigestForTeam: (
        teamId: number,
        enabled: boolean
    ) => {
        enabled: boolean
        teamId: number
    }
    updateHasSeenProductIntroFor: (
        productKey: string | ProductKey,
        value?: boolean
    ) => {
        productKey: string
        value: boolean
    }
    updateMemberJoinEmailForAllOrganizations: (
        organizationIds: string[],
        enabled: boolean
    ) => {
        enabled: boolean
        organizationIds: string[]
    }
    updateMemberJoinEmailForOrganization: (
        organizationId: string,
        enabled: boolean
    ) => {
        enabled: boolean
        organizationId: string
    }
    updatePipelineNotification: (
        pipelineId: string,
        enabled: boolean
    ) => {
        enabled: boolean
        pipelineId: string
    }
    updatePipelineNotificationForAll: (
        pipelineIds: string[],
        enabled: boolean
    ) => {
        enabled: boolean
        pipelineIds: string[]
    }
    updateRealtimeNotificationForProject: (
        teamId: number,
        types: string[],
        enabled: boolean
    ) => {
        enabled: boolean
        teamId: number
        types: string[]
    }
    updateRealtimeNotificationForTeam: (
        type: string,
        teamId: number,
        enabled: boolean
    ) => {
        enabled: boolean
        teamId: number
        type: string
    }
    updateUser: (
        user: Partial<UserType>,
        successCallback?: () => void,
        failureCallback?: () => void
    ) => {
        failureCallback: (() => void) | undefined
        successCallback: (() => void) | undefined
        user: Partial<UserType>
    }
    updateUserFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateUserSuccess: (
        user: UserType,
        payload?: {
            failureCallback: (() => void) | undefined
            successCallback: (() => void) | undefined
            user: Partial<UserType>
        }
    ) => {
        user: UserType
        payload?: {
            failureCallback: (() => void) | undefined
            successCallback: (() => void) | undefined
            user: Partial<UserType>
        }
    }
    updateWAWeeklyDigestForAllTeams: (
        teamIds: number[],
        enabled: boolean
    ) => {
        enabled: boolean
        teamIds: number[]
    }
    updateWAWeeklyDigestForTeam: (
        teamId: number,
        enabled: boolean
    ) => {
        enabled: boolean
        teamId: number
    }
    updateWeeklyDigestForAllTeams: (
        teamIds: number[],
        enabled: boolean
    ) => {
        enabled: boolean
        teamIds: number[]
    }
    updateWeeklyDigestForTeam: (
        teamId: number,
        enabled: boolean
    ) => {
        enabled: boolean
        teamId: number
    }
    upgradeImpersonation: (reason: string) => {
        reason: string
    }
    upgradeImpersonationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    upgradeImpersonationSuccess: (
        user: UserType | null,
        payload?: {
            reason: string
        }
    ) => {
        user: UserType | null
        payload?: {
            reason: string
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface userLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        hasAvailableFeature: (
            user: UserType | null
        ) => (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
        availableFeature: (
            user: UserType | null
        ) => (feature: AvailableFeature) => BillingFeatureType | null | undefined
        isProvisionedUser: (user: UserType | null) => boolean
        otherOrganizations: (user: UserType | null) => OrganizationBasicType[]
        themeMode: (user: UserType | null, optimisticThemeMode: UserTheme | null) => UserTheme
        isUserNonTechnical: (user: UserType | null) => boolean
    }
}

export type userLogicType = MakeLogicType<userLogicValues, userLogicActions, Record<string, any>, userLogicMeta>

export const userLogic = kea<userLogicType>([
    path(['scenes', 'userLogic']),
    actions(() => ({
        loadUser: (resetOnFailure?: boolean) => ({ resetOnFailure }),
        addFullStageUserFields: (fields: Partial<UserType>) => ({ fields }),
        updateCurrentOrganization: (organizationId: string, destination?: string) => ({ organizationId, destination }),
        updateCurrentOrganizationFailure: true,
        logout: (preserveLocation = false, nextUrl?: string, reason?: string) => ({
            preserveLocation,
            nextUrl,
            reason,
        }),
        upgradeImpersonation: (reason: string) => ({ reason }),
        updateUser: (user: Partial<UserType>, successCallback?: () => void, failureCallback?: () => void) => ({
            user,
            successCallback,
            failureCallback,
        }),
        cancelEmailChangeRequest: true,
        setUserScenePersonalisation: (scene: DashboardCompatibleScenes, dashboard: number) => ({ scene, dashboard }),
        // Not only product keys: the map also holds keys composed per team, and keys for surfaces
        // that are not products, which is what the endpoint accepts.
        updateHasSeenProductIntroFor: (productKey: ProductKey | string, value: boolean = true) => ({
            productKey,
            value,
        }),
        switchTeam: (teamId: string | number, destination?: string) => ({ teamId, destination }),
        deleteUser: true,
        updateWeeklyDigestForTeam: (teamId: number, enabled: boolean) => ({ teamId, enabled }),
        updateWeeklyDigestForAllTeams: (teamIds: number[], enabled: boolean) => ({ teamIds, enabled }),
        updateETWeeklyDigestForTeam: (teamId: number, enabled: boolean) => ({ teamId, enabled }),
        updateETWeeklyDigestForAllTeams: (teamIds: number[], enabled: boolean) => ({ teamIds, enabled }),
        updateWAWeeklyDigestForTeam: (teamId: number, enabled: boolean) => ({ teamId, enabled }),
        updateWAWeeklyDigestForAllTeams: (teamIds: number[], enabled: boolean) => ({ teamIds, enabled }),
        updateMemberJoinEmailForOrganization: (organizationId: string, enabled: boolean) => ({
            organizationId,
            enabled,
        }),
        updateMemberJoinEmailForAllOrganizations: (organizationIds: string[], enabled: boolean) => ({
            organizationIds,
            enabled,
        }),
        updateDataPipelineErrorThreshold: (threshold: number) => ({ threshold }),
        credentialReviewDismissed: true,
        updateRealtimeNotificationForTeam: (type: string, teamId: number, enabled: boolean) => ({
            type,
            teamId,
            enabled,
        }),
        updateRealtimeNotificationForProject: (teamId: number, types: string[], enabled: boolean) => ({
            teamId,
            types,
            enabled,
        }),
        updateAllRealtimeNotifications: (teamIds: number[], types: string[], enabled: boolean) => ({
            teamIds,
            types,
            enabled,
        }),
        updatePipelineNotification: (pipelineId: string, enabled: boolean) => ({ pipelineId, enabled }),
        updatePipelineNotificationForAll: (pipelineIds: string[], enabled: boolean) => ({ pipelineIds, enabled }),
    })),
    forms(({ actions }) => ({
        userDetails: {
            errors: ({ first_name, email }) => ({
                first_name: !first_name
                    ? 'You need to have a name.'
                    : first_name.length > 150
                      ? 'This name is too long. Please keep it under 151 characters.'
                      : null,
                email: !email
                    ? 'You need to have an email.'
                    : email.length > 254
                      ? 'This email is too long. Please keep it under 255 characters.'
                      : null,
            }),
            submit: (user) => {
                actions.updateUser(user)
            },
        },
    })),
    loaders(({ values, actions, cache }) => ({
        user: [
            // TODO: Because we don't actually load the app until this request completes, `user` is never `null` (will help simplify checks across the app)
            null as UserType | null,
            {
                loadUser: async () => {
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersRetrieve() from '~/generated/core/api' instead.
                        return await api.get<UserType>('api/users/@me/')
                    } catch (error: any) {
                        console.error(error)
                        actions.loadUserFailure(error.message)
                    }
                    return null
                },
                // No listeners, so the late fields do not rerun what a user load triggers.
                addFullStageUserFields: ({ fields }): UserType | null =>
                    values.user ? { ...values.user, ...fields } : null,
                updateUser: async ({ user, successCallback, failureCallback }): Promise<UserType> => {
                    const previousUpdate = cache.pendingUserUpdate as Promise<void> | undefined
                    let completeUpdate: () => void = () => {}
                    const pendingUpdate = new Promise<void>((resolve) => {
                        completeUpdate = resolve
                    })
                    cache.pendingUserUpdate = pendingUpdate
                    await previousUpdate

                    try {
                        if (!values.user) {
                            throw new Error('Current user has not been loaded yet, so it cannot be updated!')
                        }
                        // Full user responses can replace newer state, so account writes finish in submission order.
                        // 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.
                        const response = await api.update<UserType>('api/users/@me/', user)
                        successCallback?.()
                        return response
                    } catch (error) {
                        failureCallback?.()
                        // Returning the old user would make kea-loaders report a failed write as a success.
                        throw error
                    } finally {
                        completeUpdate()
                        if (cache.pendingUserUpdate === pendingUpdate) {
                            cache.pendingUserUpdate = undefined
                        }
                    }
                },
                cancelEmailChangeRequest: async () => {
                    if (!values.user) {
                        throw new Error('Current user has not been loaded yet, so it cannot be updated!')
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersCancelEmailChangeRequestPartialUpdate() 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 response = await api.update<UserType>('api/users/cancel_email_change_request/', {})
                        lemonToast.success('The email change request was cancelled successfully.')
                        return response
                    } catch (error: any) {
                        console.error(error)
                        lemonToast.error(
                            'Failed to cancel email change request. Please try again later or contact support.'
                        )
                        return values.user
                    }
                },
                deleteUser: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersDestroy() 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.delete('api/users/@me/').then(() => {
                        return null
                    })
                },
                setUserScenePersonalisation: async ({ scene, dashboard }) => {
                    if (!values.user) {
                        throw new Error('Current user has not been loaded yet, so it cannot be updated!')
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersScenePersonalisationCreate() 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<UserType>('api/users/@me/scene_personalisation', {
                            scene,
                            dashboard,
                        })
                    } catch (error: any) {
                        console.error(error)
                        actions.updateUserFailure(error.message)
                        return values.user
                    }
                },
                upgradeImpersonation: async ({ reason }) => {
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call to a route outside /api/, with an unchecked response type. No generated function can cover it until the route is in the OpenAPI schema.
                        await api.create('admin/impersonation/upgrade/', { reason })
                        actions.loadUser()
                        lemonToast.success('Upgraded to read-write impersonation')

                        // optimistically update user to read-write rather than
                        // waiting for `loadUser` to complete
                        return values.user ? { ...values.user, is_impersonated_read_only: false } : null
                    } catch (error: any) {
                        console.error(error)
                        lemonToast.error('Failed to upgrade impersonation')
                        return values.user
                    }
                },
            },
        ],
    })),
    reducers({
        userDetails: [
            {} as UserDetailsFormType,
            {
                loadUserSuccess: (_, { user }) => ({
                    first_name: user?.first_name || '',
                    last_name: user?.last_name || '',
                    email: user?.email || '',
                }),
                updateUserSuccess: (_, { user }) => ({
                    first_name: user?.first_name || '',
                    last_name: user?.last_name || '',
                    email: user?.email || '',
                }),
            },
        ],
        isSwitchingOrganization: [
            false,
            {
                updateCurrentOrganization: () => true,
                updateCurrentOrganizationFailure: () => false,
            },
        ],
        isImpersonationUpgradeInProgress: [
            false,
            {
                upgradeImpersonation: () => true,
                upgradeImpersonationSuccess: () => false,
                upgradeImpersonationFailure: () => false,
            },
        ],
        optimisticThemeMode: [
            null as UserTheme | null,
            {
                updateUser: (prev, { user }) => (user?.theme_mode !== undefined ? user.theme_mode : prev),
                updateUserSuccess: () => null,
                updateUserFailure: () => null,
            },
        ],
        // Set when the user clicks Continue on /account/credential-review. Suppresses
        // the post-loadUser redirect so an in-flight stale loadUser response can't
        // bounce the user back to the review screen after they've already dismissed it.
        credentialReviewDismissedInSession: [
            false,
            {
                credentialReviewDismissed: () => true,
            },
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        logout: ({ preserveLocation, nextUrl, reason }) => {
            if (cache.loggingOut) {
                return
            }
            cache.loggingOut = true
            posthog.reset()
            // Drop the address a signup or login attempt stored for the verify page
            clearPendingVerificationEmail()
            clearSQLEditorDrafts()

            // OAuth mode: there's no local Django session to end — just drop the stored cloud
            // token and return to the local login. (A cross-origin /logout POST would do nothing.)
            if (isOAuthMode()) {
                clearSession()
                window.location.href = '/login'
                return
            }

            const form = document.createElement('form')
            form.method = 'POST'
            form.action = '/logout'
            form.style.display = 'none'

            const csrfInput = document.createElement('input')
            csrfInput.type = 'hidden'
            csrfInput.name = 'csrfmiddlewaretoken'
            csrfInput.value = getCookie('posthog_csrftoken') || ''
            form.appendChild(csrfInput)

            // The server turns a known reason into the message the login page shows.
            if (reason) {
                const reasonInput = document.createElement('input')
                reasonInput.type = 'hidden'
                reasonInput.name = 'reason'
                reasonInput.value = reason
                form.appendChild(reasonInput)
            }

            if (preserveLocation || nextUrl) {
                const { pathname, search, hash } = window.location
                const nextInput = document.createElement('input')
                nextInput.type = 'hidden'
                nextInput.name = 'next'
                nextInput.value = nextUrl || pathname + search + hash
                form.appendChild(nextInput)
            }

            document.body.appendChild(form)
            form.submit()
        },
        loadUserSuccess: ({ user }) => {
            if (user && user.uuid) {
                // OAuth mode has no server-rendered app context, so seed the current ids from the
                // freshly loaded remote user. This makes them available synchronously before the first
                // project-scoped URL is built, avoiding "Project ID is not known." (and the sibling
                // user/org id errors) on bootstrap. The API layer reads default project/team-id params
                // from ApiConfig; getAppContext's synchronous getters read the pushed ids (it stays a
                // leaf module — importing ApiConfig there would create a module-init cycle).
                if (isOAuthMode()) {
                    if (user.team) {
                        ApiConfig.setCurrentTeamId(user.team.id)
                        ApiConfig.setCurrentProjectId(user.team.project_id)
                    }
                    if (user.organization) {
                        ApiConfig.setCurrentOrganizationId(user.organization.id)
                    }
                    setOAuthContextIds({
                        teamId: user.team?.id,
                        organizationId: user.organization?.id,
                        userId: user.uuid,
                    })
                }

                // loadPostHogJS already identified the user in the page and loaded flags for them, so
                // flags reload here only for a user that changed without a page load.
                if (posthog && identifyUserInPostHog(posthog, user)) {
                    posthog.reloadFeatureFlags()
                }

                // First-login interstitial: route users with unreviewed pre-existing API keys
                // to the credential review screen before they enter the app. Gated server-side
                // by UserSerializer.get_requires_credential_review.
                //
                // credentialReviewDismissedInSession suppresses a bounce-back if a loadUser
                // call that was in-flight at dismiss time resolves later with stale state.
                if (
                    user.requires_credential_review &&
                    !values.credentialReviewDismissedInSession &&
                    !router.values.location.pathname.startsWith('/account/credential-review')
                ) {
                    const { pathname, search, hash } = router.values.location
                    router.actions.push(urls.credentialReview(`${pathname}${search}${hash}`))
                }
            }
        },
        updateUserSuccess: () => {
            lemonToast.dismiss('updateUser')
            lemonToast.success('Preferences saved', {
                toastId: 'updateUser',
            })
        },
        updateUserFailure: ({ errorObject }) => {
            lemonToast.dismiss('updateUser')
            lemonToast.error(errorObject?.detail || 'Error saving preferences', {
                toastId: 'updateUser',
            })
        },
        deleteUserSuccess: () => {
            actions.logout()
            lemonToast.success('Account deleted', {
                toastId: 'deleteUser',
            })
        },
        deleteUserFailure: () => {
            lemonToast.error('Error deleting account', {
                toastId: 'deleteUser',
            })
        },
        updateCurrentOrganization: async ({ organizationId, destination }, breakpoint) => {
            if (values.user?.organization?.id === organizationId) {
                return
            }
            await breakpoint(10)
            try {
                // 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 })
            } catch {
                actions.updateCurrentOrganizationFailure()
                lemonToast.error('Could not switch organization. Try again.')
                return
            }

            sidePanelStateLogic.findMounted()?.actions.closeSidePanel()

            window.location.href = destination || '/'
        },
        updateHasSeenProductIntroFor: async ({ productKey, value }, breakpoint) => {
            await breakpoint(10)
            try {
                // Its own endpoint rather than a field on the user PATCH: that one needs a recently
                // authenticated session, so a risk step-up would answer a dismissal with the re-auth modal.
                // It also merges the key server-side, so two tabs can't drop each other's write.
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersProductIntroSeenPartialUpdate() from '~/generated/core/api' instead.
                await api.update('api/users/@me/product_intro_seen', { product_key: productKey, seen: value })
                actions.loadUser()
            } catch (error: any) {
                // Marking an intro seen runs behind whatever the user is already doing, so a failure is
                // logged rather than surfaced: a toast would land on top of the intro they just dismissed.
                // The intro comes back next visit, which is the honest outcome of a write that didn't land.
                console.error(error)
            }
        },
        switchTeam: ({ teamId, destination }) => {
            sidePanelStateLogic.findMounted()?.actions.closeSidePanel()

            window.location.href = destination || urls.project(teamId)
        },
        updateWeeklyDigestForTeam: ({ teamId, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }

            actions.updateUser({
                notification_settings: {
                    ...values.user.notification_settings,
                    project_weekly_digest_disabled: {
                        ...values.user.notification_settings.project_weekly_digest_disabled,
                        [teamId]: !enabled,
                    },
                },
            })
        },
        updateWeeklyDigestForAllTeams: ({ teamIds, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }

            const projectWeeklyDigestSettings = {
                ...values.user.notification_settings.project_weekly_digest_disabled,
            }
            teamIds?.forEach((teamId) => {
                projectWeeklyDigestSettings[teamId] = !enabled
            })

            actions.updateUser({
                notification_settings: {
                    ...values.user.notification_settings,
                    project_weekly_digest_disabled: projectWeeklyDigestSettings,
                },
            })
        },
        updateETWeeklyDigestForTeam: ({ teamId, enabled }) => {
            updateDigestProjectSetting('error_tracking_weekly_digest_project_enabled', teamId, enabled, values, actions)
        },
        updateETWeeklyDigestForAllTeams: ({ teamIds, enabled }) => {
            updateDigestProjectSettings(
                'error_tracking_weekly_digest_project_enabled',
                teamIds,
                enabled,
                values,
                actions
            )
        },
        updateWAWeeklyDigestForTeam: ({ teamId, enabled }) => {
            updateDigestProjectSetting('web_analytics_weekly_digest_project_enabled', teamId, enabled, values, actions)
        },
        updateWAWeeklyDigestForAllTeams: ({ teamIds, enabled }) => {
            updateDigestProjectSettings(
                'web_analytics_weekly_digest_project_enabled',
                teamIds,
                enabled,
                values,
                actions
            )
        },
        updateMemberJoinEmailForOrganization: ({ organizationId, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }

            actions.updateUser({
                notification_settings: {
                    ...values.user.notification_settings,
                    organization_member_join_email_disabled: {
                        ...values.user.notification_settings.organization_member_join_email_disabled,
                        [organizationId]: !enabled,
                    },
                },
            })
        },
        updateMemberJoinEmailForAllOrganizations: ({ organizationIds, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }

            const organizationMemberJoinEmailDisabled = {
                ...values.user.notification_settings.organization_member_join_email_disabled,
            }
            organizationIds.forEach((id) => {
                organizationMemberJoinEmailDisabled[id] = !enabled
            })

            actions.updateUser({
                notification_settings: {
                    ...values.user.notification_settings,
                    organization_member_join_email_disabled: organizationMemberJoinEmailDisabled,
                },
            })
        },
        updateRealtimeNotificationForTeam: ({ type, teamId, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }
            const current = values.user.notification_settings.realtime_notifications_disabled ?? {}
            const typeMap = { ...current[type], [String(teamId)]: !enabled }
            actions.updateUser({
                notification_settings: {
                    realtime_notifications_disabled: { ...current, [type]: typeMap },
                } as NotificationSettings,
            })
        },
        updateRealtimeNotificationForProject: ({ teamId, types, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }
            const current = values.user.notification_settings.realtime_notifications_disabled ?? {}
            const next = { ...current }
            for (const type of types) {
                next[type] = { ...next[type], [String(teamId)]: !enabled }
            }
            actions.updateUser({
                notification_settings: {
                    realtime_notifications_disabled: next,
                } as NotificationSettings,
            })
        },
        updateAllRealtimeNotifications: ({ teamIds, types, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }
            const current = values.user.notification_settings.realtime_notifications_disabled ?? {}
            const next = { ...current }
            for (const type of types) {
                const typeMap = { ...next[type] }
                for (const teamId of teamIds) {
                    typeMap[String(teamId)] = !enabled
                }
                next[type] = typeMap
            }
            actions.updateUser({
                notification_settings: {
                    realtime_notifications_disabled: next,
                } as NotificationSettings,
            })
        },
        updateDataPipelineErrorThreshold: async ({ threshold }, breakpoint) => {
            await breakpoint(500)

            if (isNaN(threshold) || threshold < 0 || threshold > 100) {
                return
            }

            values.user?.notification_settings &&
                actions.updateUser({
                    notification_settings: {
                        ...values.user?.notification_settings,
                        data_pipeline_error_threshold: threshold / 100,
                    },
                })
        },
        updatePipelineNotification: ({ pipelineId, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }

            actions.updateUser({
                notification_settings: {
                    ...values.user.notification_settings,
                    pipeline_notifications_disabled: {
                        ...values.user.notification_settings.pipeline_notifications_disabled,
                        [pipelineId]: !enabled,
                    },
                },
            })
        },
        updatePipelineNotificationForAll: ({ pipelineIds, enabled }) => {
            if (!values.user?.notification_settings) {
                return
            }

            const pipelineNotificationsDisabled = {
                ...values.user.notification_settings.pipeline_notifications_disabled,
            }
            pipelineIds.forEach((id) => {
                pipelineNotificationsDisabled[id] = !enabled
            })

            actions.updateUser({
                notification_settings: {
                    ...values.user.notification_settings,
                    pipeline_notifications_disabled: pipelineNotificationsDisabled,
                },
            })
        },
    })),
    selectors({
        hasAvailableFeature: [
            (s) => [s.user],
            (user: UserType | null) => {
                return (feature: AvailableFeature, currentUsage?: number) => {
                    const availableProductFeatures = user?.organization?.available_product_features
                    if (availableProductFeatures && availableProductFeatures.length > 0) {
                        const availableFeature = availableProductFeatures.find((obj) => obj.key === feature)
                        return availableFeature
                            ? currentUsage
                                ? availableFeature?.limit
                                    ? availableFeature?.limit > currentUsage
                                    : true
                                : true
                            : false
                    }
                    return false
                }
            },
        ],
        availableFeature: [
            (s) => [s.user],
            (user: UserType | null) => {
                return (feature: AvailableFeature) => {
                    const availableProductFeatures = user?.organization?.available_product_features
                    if (availableProductFeatures && availableProductFeatures.length > 0) {
                        return availableProductFeatures.find((obj) => obj.key === feature)
                    }
                    return null
                }
            },
        ],
        // True for accounts created by a partner drop flow (onboarding skipped with reason
        // 'provisioned'). Drives the provisioned welcome experience: welcome dialog, quick-start
        // seeding, and the homepage banner.
        isProvisionedUser: [
            (s) => [s.user],
            (user: UserType | null): boolean => user?.onboarding_skipped_reason === 'provisioned',
        ],

        otherOrganizations: [
            (s) => [s.user],
            (user: UserType | null): OrganizationBasicType[] =>
                user
                    ? user.organizations
                          ?.filter((organization) => organization.id !== user.organization?.id)
                          .sort((orgA, orgB) =>
                              orgA.id === user?.organization?.id ? -2 : orgA.name.localeCompare(orgB.name)
                          ) || []
                    : [],
        ],

        themeMode: [
            (s) => [s.user, s.optimisticThemeMode],
            (user: UserType | null, optimisticThemeMode: UserTheme | null): UserTheme => {
                return optimisticThemeMode ?? user?.theme_mode ?? 'light'
            },
        ],

        isUserNonTechnical: [
            (s) => [s.user],
            (user: UserType | null): boolean => {
                const nonTechnicalRoles = [
                    UserRole.Founder,
                    UserRole.Leadership,
                    UserRole.Marketing,
                    UserRole.Sales,
                    UserRole.Other,
                ]
                return user?.role_at_organization
                    ? nonTechnicalRoles.includes(user.role_at_organization as UserRole)
                    : false
            },
        ],
    }),
    afterMount(({ actions, cache }) => {
        cache.disposables.add(
            () => {
                window.addEventListener('storage', clearSQLEditorDraftFromStorageEvent)
                return () => window.removeEventListener('storage', clearSQLEditorDraftFromStorageEvent)
            },
            'sqlEditorDraftLogout',
            { pauseOnPageHidden: false }
        )
        const preloadedUser = getAppContext()?.current_user
        if (preloadedUser) {
            actions.loadUserSuccess(preloadedUser)
        } else if (preloadedUser === null) {
            actions.loadUserFailure('Logged out')
        } else {
            actions.loadUser()
        }
    }),
])