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.

6.3 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

import api from 'lib/api'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { UserType } from '~/types'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface staffUsersLogicValues {
    user: UserType | null // userLogic
    allUsers: UserType[]
    allUsersLoading: boolean
    nonStaffUsers: UserType[]
    staffUserToBeDeleted: UserType | null
    staffUsers: UserType[]
    staffUsersToBeAdded: string[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface staffUsersLogicActions {
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    addStaffUsers: () => {
        value: true
    }
    addStaffUsersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    addStaffUsersSuccess: (
        allUsers: UserType[],
        payload?: {
            value: true
        }
    ) => {
        allUsers: UserType[]
        payload?: {
            value: true
        }
    }
    deleteStaffUser: (userUuid: string) => {
        userUuid: string
    }
    deleteStaffUserFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteStaffUserSuccess: (
        allUsers: UserType[],
        payload?: {
            userUuid: string
        }
    ) => {
        allUsers: UserType[]
        payload?: {
            userUuid: string
        }
    }
    loadAllUsers: () => any
    loadAllUsersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAllUsersSuccess: (
        allUsers: UserType[],
        payload?: any
    ) => {
        allUsers: UserType[]
        payload?: any
    }
    setStaffUserToBeDeleted: (user: UserType | null) => {
        user: UserType | null
    }
    setStaffUsersToBeAdded: (userUuids: string[]) => {
        userUuids: string[]
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface staffUsersLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        staffUsers: (allUsers: UserType[]) => UserType[]
        nonStaffUsers: (allUsers: UserType[]) => UserType[]
    }
}

export type staffUsersLogicType = MakeLogicType<
    staffUsersLogicValues,
    staffUsersLogicActions,
    Record<string, any>,
    staffUsersLogicMeta
>

export const staffUsersLogic = kea<staffUsersLogicType>([
    path(['scenes', 'instance', 'SystemStatus', 'staffUsersLogic']),
    connect(() => ({
        values: [userLogic, ['user']],
        actions: [userLogic, ['loadUser']],
    })),
    actions({
        setStaffUsersToBeAdded: (userUuids: string[]) => ({ userUuids }),
        addStaffUsers: true,
        setStaffUserToBeDeleted: (user: UserType | null) => ({ user }),
        deleteStaffUser: (userUuid: string) => ({ userUuid }),
    }),
    loaders(({ actions, values }) => ({
        allUsers: [
            [] as UserType[],
            {
                loadAllUsers: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersList() from '~/generated/core/api' instead.
                    return (await api.get('api/users')).results ?? []
                },
                addStaffUsers: async () => {
                    const { staffUsersToBeAdded, allUsers } = values
                    actions.setStaffUsersToBeAdded([])
                    const newStaffUsers = await Promise.all(
                        staffUsersToBeAdded.map(
                            // 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.
                            async (userUuid) => await api.update<UserType>(`api/users/${userUuid}`, { is_staff: true })
                        )
                    )
                    const updatedAllUsers: UserType[] = [
                        ...allUsers.filter(({ uuid }) => !staffUsersToBeAdded.includes(uuid)),
                        ...newStaffUsers,
                    ]
                    updatedAllUsers.sort((a, b) => a.first_name.localeCompare(b.first_name))
                    return updatedAllUsers
                },
                deleteStaffUser: async ({ userUuid }) => {
                    // 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<UserType>(`api/users/${userUuid}`, { is_staff: false })
                    if (values.user?.uuid === userUuid) {
                        actions.loadUser() // Loads the main user object to properly reflect staff user changes
                        router.actions.push(urls.projectRoot())
                    }
                    const updatedAllUsers = [...values.allUsers]
                    for (const user of updatedAllUsers) {
                        if (user.uuid === userUuid) {
                            user.is_staff = false
                        }
                    }
                    return updatedAllUsers
                },
            },
        ],
    })),
    reducers({
        staffUsersToBeAdded: [
            [] as string[],
            {
                setStaffUsersToBeAdded: (_, { userUuids }) => userUuids,
            },
        ],
        staffUserToBeDeleted: [
            null as UserType | null,
            {
                setStaffUserToBeDeleted: (_, { user }) => user,
            },
        ],
    }),
    selectors({
        staffUsers: [
            (s) => [s.allUsers],
            (allUsers: UserType[]): UserType[] => allUsers.filter((user) => user.is_staff),
        ],
        nonStaffUsers: [
            (s) => [s.allUsers],
            (allUsers: UserType[]): UserType[] => allUsers.filter((user) => !user.is_staff),
        ],
    }),
    events(({ actions }) => ({
        afterMount: [actions.loadAllUsers],
    })),
])