: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { ConcurrencyController } from 'lib/utils/concurrencyController'
import { fullNameOrEmail, pluralize } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'
import { membersLogic } from '~/models/membersLogic'
import { OrganizationMemberType } from '~/types'
import { alertsPartialUpdate } from 'products/alerts/frontend/generated/api'
import { membersDestroy, membersOffboardingPreviewRetrieve } from 'products/platform_features/frontend/generated/api'
import type { MemberOffboardingResourceApi } from 'products/platform_features/frontend/generated/api.schemas'
import { subscriptionsPartialUpdate } from 'products/subscriptions/frontend/generated/api'
import type { OrganizationType, UserType } from '../../../types'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface memberOffboardingLogicValues {
currentOrganization: OrganizationType | null // organizationLogic
user: UserType | null // userLogic
getSelectionLabel: (selectedKeys: readonly string[]) => string
keep: string[]
loadError: string | null
member: OrganizationMemberType | null
publicResources: MemberOffboardingResourceApi[]
removed: boolean
removedLoading: boolean
resources: MemberOffboardingResourceApi[] | null
resourcesLoading: boolean
savingResourceIds: string[]
savingResources: boolean
savingResourcesLoading: boolean
subscriptions: MemberOffboardingResourceApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface memberOffboardingLogicActions {
loadMemberScopedApiKeys: (member: OrganizationMemberType) => {
member: OrganizationMemberType
} // membersLogic
postRemoveMember: (userUuid: string) => {
userUuid: string
} // membersLogic
close: () => {
value: true
}
disableResources: (ids: string[]) => {
ids: string[]
}
loadResources: () => {
value: true
}
loadResourcesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadResourcesSuccess: (
resources: MemberOffboardingResourceApi[] | null,
payload?: {
value: true
}
) => {
resources: MemberOffboardingResourceApi[] | null
payload?: {
value: true
}
}
open: (member: OrganizationMemberType) => {
member: OrganizationMemberType
}
remove: () => {
value: true
}
removeFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
removeSuccess: (
removed: boolean,
payload?: {
value: true
}
) => {
removed: boolean
payload?: {
value: true
}
}
saveResources: ({ ids, enabled }: { enabled: boolean; ids: string[] }) => {
ids: string[]
enabled: boolean
}
saveResourcesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
saveResourcesSuccess: (
savingResources: boolean,
payload?: {
ids: string[]
enabled: boolean
}
) => {
savingResources: boolean
payload?: {
ids: string[]
enabled: boolean
}
}
setKeep: (
id: string,
keep: boolean
) => {
id: string
keep: boolean
}
setKeptResources: (ids: string[]) => {
ids: string[]
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface memberOffboardingLogicMeta {
__keaTypeGenInternalSelectorTypes: {
publicResources: (resources: MemberOffboardingResourceApi[] | null) => MemberOffboardingResourceApi[]
subscriptions: (resources: MemberOffboardingResourceApi[] | null) => MemberOffboardingResourceApi[]
getSelectionLabel: (
resources: MemberOffboardingResourceApi[] | null
) => (selectedKeys: readonly string[]) => string
}
}
export type memberOffboardingLogicType = MakeLogicType<
memberOffboardingLogicValues,
memberOffboardingLogicActions,
Record<string, any>,
memberOffboardingLogicMeta
>
export const memberOffboardingLogic = kea<memberOffboardingLogicType>([
path(['scenes', 'settings', 'organization', 'memberOffboardingLogic']),
connect({
values: [organizationLogic, ['currentOrganization'], userLogic, ['user']],
actions: [membersLogic, ['loadMemberScopedApiKeys', 'postRemoveMember']],
}),
actions({
open: (member: OrganizationMemberType) => ({ member }),
close: true,
setKeep: (id: string, keep: boolean) => ({ id, keep }),
disableResources: (ids: string[]) => ({ ids }),
setKeptResources: (ids: string[]) => ({ ids }),
loadResources: true,
remove: true,
}),
reducers({
member: [null as OrganizationMemberType | null, { open: (_, { member }) => member, close: () => null }],
keep: [
[] as string[],
{
open: () => [],
setKeptResources: (_, { ids }) => ids,
},
],
savingResourceIds: [
[] as string[],
{
open: () => [],
saveResources: (_, { ids }) => ids,
saveResourcesSuccess: () => [],
saveResourcesFailure: () => [],
},
],
loadError: [
null as string | null,
{ open: () => null, loadResources: () => null, loadResourcesFailure: (_, { error }) => error },
],
}),
loaders(({ values, actions }) => ({
resources: {
__default: null as MemberOffboardingResourceApi[] | null,
loadResources: async (_, breakpoint) => {
const member = values.member
if (!member) {
return null
}
const resources = await membersOffboardingPreviewRetrieve(
values.currentOrganization?.id ?? '@current',
member.user.uuid
)
breakpoint()
return resources
},
},
savingResources: {
__default: false,
saveResources: async ({ ids, enabled }: { ids: string[]; enabled: boolean }) => {
if (!values.member) {
return false
}
const selected = (values.resources ?? []).filter((resource) => ids.includes(resource.id))
const concurrency = new ConcurrencyController(5)
const results = await Promise.allSettled(
selected.map((resource) =>
concurrency.run({
fn: async () => {
const resourceId = resource.resource_id
const projectId = String(resource.team_id)
if (resource.kind === 'subscription') {
await subscriptionsPartialUpdate(projectId, Number(resourceId), {
enabled,
send_test_now: false,
})
return resource.id
}
if (resource.kind === 'alert') {
await alertsPartialUpdate(projectId, resourceId, { enabled })
return resource.id
}
await api.sharing.update(
{
teamId: resource.team_id,
...(resource.kind === 'dashboard'
? { dashboardId: Number(resourceId) }
: resource.kind === 'insight'
? { insightId: Number(resourceId) }
: resource.kind === 'notebook'
? { notebookShortId: resourceId }
: { recordingId: resourceId }),
},
{ enabled }
)
return resource.id
},
})
)
)
const savedIds = results.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []))
actions.setKeptResources(
enabled
? [...new Set([...values.keep, ...savedIds])]
: values.keep.filter((id) => !savedIds.includes(id))
)
const failed = selected.filter((_, index) => results[index].status === 'rejected')
if (failed.length) {
const reasons = [
...new Set(
results.flatMap((result) =>
result.status === 'rejected' &&
result.reason instanceof ApiError &&
result.reason.detail
? [result.reason.detail]
: []
)
),
]
lemonToast.error(
`Couldn't update ${failed.map((resource) => resource.name).join(', ')}. ${reasons.join(' ') || 'Please try again.'}`
)
}
return true
},
},
removed: {
__default: false,
remove: async () => {
if (!values.member || values.resourcesLoading || values.savingResourcesLoading) {
return false
}
const member = values.member
await membersDestroy(values.currentOrganization?.id ?? '@current', member.user.uuid)
lemonToast.success(`Removed ${fullNameOrEmail(member.user)} from organization`)
actions.close()
actions.postRemoveMember(member.user.uuid)
return true
},
},
})),
selectors({
publicResources: [
(s) => [s.resources],
(resources: MemberOffboardingResourceApi[] | null): MemberOffboardingResourceApi[] =>
(resources ?? []).filter((resource) => resource.kind !== 'subscription' && resource.kind !== 'alert'),
],
subscriptions: [
(s) => [s.resources],
(resources: MemberOffboardingResourceApi[] | null): MemberOffboardingResourceApi[] =>
(resources ?? []).filter((resource) => resource.kind === 'subscription' || resource.kind === 'alert'),
],
getSelectionLabel: [
(s) => [s.resources],
(resources: MemberOffboardingResourceApi[] | null) =>
(selectedKeys: ReadonlyArray<string>): string => {
const selected = new Set(selectedKeys)
const counts = new Map<string, number>()
for (const resource of resources ?? []) {
if (selected.has(resource.id)) {
counts.set(resource.kind, (counts.get(resource.kind) ?? 0) + 1)
}
}
const labels = ['dashboard', 'insight', 'notebook', 'recording', 'subscription', 'alert']
.filter((kind) => counts.has(kind))
.map((kind) => pluralize(counts.get(kind)!, kind))
return labels.join(', ')
},
],
}),
listeners(({ actions, values }) => ({
setKeep: ({ id, keep }) => {
if (!values.savingResourcesLoading && !values.removedLoading) {
actions.saveResources({ ids: [id], enabled: keep })
}
},
disableResources: ({ ids }) => {
if (!values.savingResourcesLoading && !values.removedLoading && ids.length > 0) {
actions.saveResources({ ids, enabled: false })
}
},
saveResourcesFailure: () => {
lemonToast.error("Couldn't save changes. Please try again.")
},
loadResourcesSuccess: ({ resources }) => {
actions.setKeptResources(
values.member?.user.uuid === values.user?.uuid ? [] : (resources ?? []).map((resource) => resource.id)
)
},
open: ({ member }) => {
actions.loadMemberScopedApiKeys(member)
actions.loadResources()
},
})),
])