: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, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
import api, { ApiConfig } from 'lib/api'
import { ApiError } from 'lib/api-error'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { OrganizationMembershipLevel } from 'lib/constants'
import { IconSwapHoriz } from 'lib/lemon-ui/icons'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DEFAULT_CURRENCY } from 'lib/utils/currency'
import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
import {
type ProductCrossSellProperties,
type ProductIntentProperties,
addProductIntent,
addProductIntentForCrossSell,
} from 'lib/utils/product-intents'
import { identifierToHuman } from 'lib/utils/strings'
import {
CurrencyCode,
CustomerAnalyticsConfig,
type ProductIntentContext,
ProductKey,
} from '~/queries/schema/schema-general'
import { ProjectType, TeamPublicType, TeamType } from '~/types'
import type { FeatureFlagsSet } from '../lib/logic/featureFlagLogic'
import { organizationLogic } from './organizationLogic'
import { projectLogic } from './projectLogic'
import { userLogic } from './userLogic'
const parseUpdatedAttributeName = (attr: keyof TeamType | null): string => {
if (attr === 'app_urls') {
return 'Authorized URLs'
}
if (attr === 'web_analytics_pre_aggregated_tables_enabled') {
return 'New query engine'
}
if (attr === 'session_recording_minimum_duration_milliseconds') {
return 'Session recording minimum duration'
}
if (attr === 'feature_flag_policy_config') {
return 'Feature flag settings'
}
return attr ? identifierToHuman(attr) : 'Project'
}
/** Blocklist entries are third-party IP addresses and domains, so analytics gets only their counts. */
function featureFlagPolicyConfigForAnalytics(
config: TeamType['feature_flag_policy_config']
): Record<string, boolean | number | undefined> | undefined {
if (!config) {
return undefined
}
return {
require_tags: config.require_tags,
blocked_hosts_count: config.blocked_hosts?.length,
blocked_ips_count: config.blocked_ips?.length,
}
}
/** Return whether the provided value is a full TeamType object that's only available when authenticated. */
export function isAuthenticatedTeam(team: TeamType | TeamPublicType | undefined | null): team is TeamType {
return !!team && 'api_token' in team
}
/**
* Product-intent endpoints echo a full team serialized from a snapshot taken when their request
* started. Replacing `currentTeam` wholesale with that snapshot can clobber fields committed by a
* concurrent team PATCH — e.g. the onboarding-completion PATCH racing `complete_product_onboarding`
* loses `has_completed_onboarding_for`, so `hasOnboardedAnyProduct` flips back to false and
* sceneLogic bounces the user into /onboarding on every navigation. Keep the local team and take
* only `product_intents`, the one field these endpoints actually change.
*/
function withProductIntentsFrom(
currentTeam: TeamType | TeamPublicType | null,
response: TeamType | null
): TeamType | TeamPublicType | null {
if (!currentTeam || !response) {
return response ?? currentTeam
}
if (response.id !== currentTeam.id) {
// The response is for a different team than the one now active (the team switched while
// the request was in flight) — don't graft the old team's intents onto the current one.
return currentTeam
}
return { ...currentTeam, product_intents: response.product_intents }
}
export interface FrequentMistakeAdvice {
key: string
type: 'event' | 'person'
fix: string
}
export interface ProductOnboardingCompleteProperties {
product_type: ProductKey
intent_context?: ProductIntentContext
}
export async function completeProductOnboarding(
teamId: TeamType['id'] | string,
{ product_type, intent_context }: ProductOnboardingCompleteProperties
): Promise<TeamType | null> {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsCompleteProductOnboardingPartialUpdate() 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.update(`api/projects/${teamId}/complete_product_onboarding`, {
product_type,
intent_context,
})
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
currentProject: ProjectType | null // projectLogic
baseCurrency: CurrencyCode
currentProjectId: number | string
currentTeam: TeamPublicType | TeamType | null
currentTeamId: number | null
currentTeamIdStrict: number | string
currentTeamLoading: boolean
customerAnalyticsConfig: CustomerAnalyticsConfig
demoOnlyProject: boolean
hasOnboardedAnyProduct: boolean
isCurrentProjectAccessDenied: boolean
isCurrentTeamUnavailable: boolean
isTeamTokenResetAvailable: boolean
teamBeingDeleted: TeamType | null
testAccountFilterFrequentMistakes: FrequentMistakeAdvice[]
timezone: string
weekStartDay: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamLogicActions {
loadCurrentOrganization: () => any // organizationLogic
loadCurrentProjectSuccess: (
currentProject: ProjectType | null,
payload?: any
) => {
currentProject: ProjectType | null
payload?: any
} // projectLogic
updateCurrentProjectSuccess: (
currentProject: ProjectType,
payload?: Partial<ProjectType> | undefined
) => {
currentProject: ProjectType
payload?: Partial<ProjectType>
} // projectLogic
loadUser: (resetOnFailure?: boolean | undefined) => {
resetOnFailure: boolean | undefined
} // userLogic
switchTeam: (
teamId: number | string,
destination?: string | undefined
) => {
destination: string | undefined
teamId: number | string
} // userLogic
addFullStageTeamFields: (fields: Partial<TeamType>) => Partial<TeamType>
addFullStageTeamFieldsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
addFullStageTeamFieldsSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: Partial<TeamType>
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: Partial<TeamType>
}
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties
addProductIntentFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
addProductIntentForCrossSell: (properties: ProductCrossSellProperties) => ProductCrossSellProperties
addProductIntentForCrossSellFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
addProductIntentForCrossSellSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: ProductCrossSellProperties
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: ProductCrossSellProperties
}
addProductIntentSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: ProductIntentProperties
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: ProductIntentProperties
}
createTeam: ({ name, is_demo }: { is_demo: boolean; name: string }) => {
name: string
is_demo: boolean
}
createTeamFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
createTeamSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: {
name: string
is_demo: boolean
}
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: {
name: string
is_demo: boolean
}
}
currentProjectAccessDenied: () => {
value: true
}
deleteSecretTokenBackup: () => any
deleteSecretTokenBackupFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
deleteSecretTokenBackupSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: any
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: any
}
deleteTeam: (team: TeamType) => {
team: TeamType
}
deleteTeamFailure: () => {
value: true
}
deleteTeamSuccess: () => {
value: true
}
loadCurrentTeam: () => any
loadCurrentTeamFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadCurrentTeamSuccess: (
currentTeam: TeamPublicType | null,
payload?: any
) => {
currentTeam: TeamPublicType | null
payload?: any
}
recordProductIntentOnboardingComplete: (
properties: ProductOnboardingCompleteProperties
) => ProductOnboardingCompleteProperties
recordProductIntentOnboardingCompleteFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
recordProductIntentOnboardingCompleteSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: ProductOnboardingCompleteProperties
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: ProductOnboardingCompleteProperties
}
refreshCurrentTeam: () => any
refreshCurrentTeamFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
refreshCurrentTeamSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: any
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: any
}
resetToken: () => any
resetTokenFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
resetTokenSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: any
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: any
}
rotateSecretToken: () => any
rotateSecretTokenFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
rotateSecretTokenSuccess: (
currentTeam: TeamPublicType | TeamType | null,
payload?: any
) => {
currentTeam: TeamPublicType | TeamType | null
payload?: any
}
updateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType>
updateCurrentTeamFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
updateCurrentTeamSuccess: (
currentTeam: TeamPublicType | TeamType,
payload?: Partial<TeamType>
) => {
currentTeam: TeamPublicType | TeamType
payload?: Partial<TeamType>
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamLogicMeta {
__keaTypeGenInternalSelectorTypes: {
hasOnboardedAnyProduct: (currentTeam: TeamPublicType | TeamType | null) => boolean
currentTeamId: (currentTeam: TeamPublicType | TeamType | null) => number | null
currentTeamIdStrict: (currentTeam: TeamPublicType | TeamType | null) => number | string
currentProjectId: (currentTeam: TeamPublicType | TeamType | null) => number | string
isCurrentTeamUnavailable: (
currentTeam: TeamPublicType | TeamType | null,
currentTeamLoading: boolean
) => boolean
demoOnlyProject: (
currentTeam: TeamPublicType | TeamType | null,
currentOrganization: null | import('~/types').OrganizationType
) => boolean
timezone: (currentTeam: TeamPublicType | TeamType | null) => string
weekStartDay: (currentTeam: TeamPublicType | TeamType | null) => number
isTeamTokenResetAvailable: (currentTeam: TeamPublicType | TeamType | null) => boolean
testAccountFilterFrequentMistakes: (currentTeam: TeamPublicType | TeamType | null) => FrequentMistakeAdvice[]
baseCurrency: (currentTeam: TeamPublicType | TeamType | null) => CurrencyCode
customerAnalyticsConfig: (currentTeam: TeamPublicType | TeamType | null) => CustomerAnalyticsConfig
}
}
export type teamLogicType = MakeLogicType<teamLogicValues, teamLogicActions, Record<string, any>, teamLogicMeta>
export const teamLogic = kea<teamLogicType>([
path(['scenes', 'teamLogic']),
connect(() => ({
values: [projectLogic, ['currentProject'], featureFlagLogic, ['featureFlags']],
actions: [
userLogic,
['loadUser', 'switchTeam'],
organizationLogic,
['loadCurrentOrganization'],
projectLogic,
['loadCurrentProjectSuccess', 'updateCurrentProjectSuccess'],
],
})),
actions({
currentProjectAccessDenied: true,
deleteTeam: (team: TeamType) => ({ team }),
deleteTeamSuccess: true,
deleteTeamFailure: true,
}),
reducers({
isCurrentProjectAccessDenied: [false, { currentProjectAccessDenied: () => true }],
teamBeingDeleted: [
null as TeamType | null,
{
deleteTeam: (_, { team }) => team,
deleteTeamSuccess: () => null,
deleteTeamFailure: () => null,
},
],
}),
loaders(({ values, actions }) => ({
currentTeam: [
null as TeamType | TeamPublicType | null,
{
loadCurrentTeam: async () => {
if (!isUserLoggedIn()) {
// If user is anonymous (i.e. viewing a shared dashboard logged out), don't load authenticated stuff
return null
}
try {
// @current is the user's server-side current project, which another tab can change.
// Once this tab has a team, reload its project by id so its API calls stay in it.
// The endpoint looks up project ids, and a team id can differ from its project id.
const projectId = values.currentTeam?.project_id ?? '@current'
// 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.
return await api.get(`api/projects/${projectId}`)
} catch {
return values.currentTeam
}
},
// No listeners, so the late fields do not rerun what a team load triggers.
addFullStageTeamFields: (fields: Partial<TeamType>): TeamType | TeamPublicType | null =>
values.currentTeam ? ({ ...values.currentTeam, ...fields } as TeamType | TeamPublicType) : null,
refreshCurrentTeam: async () => {
const projectId = values.currentTeam?.project_id
if (!projectId) {
return values.currentTeam
}
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.
return await api.get(`api/projects/${projectId}`)
} catch {
return values.currentTeam
}
},
updateCurrentTeam: async (payload: Partial<TeamType>, breakpoint) => {
if (!values.currentTeam) {
throw new Error('Current team has not been loaded yet, so it cannot be updated!')
}
// session replay config is nested, so we need to make sure we don't overwrite config
if (payload.session_replay_config) {
payload.session_replay_config = {
...values.currentTeam.session_replay_config,
...payload.session_replay_config,
}
}
let patchedTeam: TeamType | TeamPublicType
if (Object.keys(payload).length === 1 && payload.name && values.currentTeam.project_id) {
// Renames go through the project id, because that mirrors the name onto the
// passthrough team server-side. Every other patch goes through the team id.
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsPartialUpdate() from '~/generated/core/api' instead.
const patchedProject = await api.update<ProjectType>(
`api/projects/${values.currentTeam.project_id}`,
{ name: payload.name }
)
breakpoint()
// Sync projectLogic too, as surfaces like the project switcher read currentProject.name
actions.loadCurrentProjectSuccess(patchedProject)
patchedTeam = { ...values.currentTeam, name: patchedProject.name }
} else {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsPartialUpdate() from '~/generated/core/api' instead.
patchedTeam = await api.update(`api/projects/${values.currentTeam.id}`, payload)
breakpoint()
}
// We need to reload current org (which lists its teams) in organizationLogic
actions.loadCurrentOrganization()
/* Notify user the update was successful */
const updatedAttribute =
Object.keys(payload).length === 1 ? (Object.keys(payload)[0] as keyof TeamType) : null
let message: string
if (updatedAttribute === 'feature_flag_confirmation_enabled') {
message = payload.feature_flag_confirmation_enabled
? 'Feature flag confirmation enabled'
: 'Feature flag confirmation disabled'
} else if (updatedAttribute === 'default_evaluation_contexts_enabled') {
message = payload.default_evaluation_contexts_enabled
? 'Default evaluation contexts enabled'
: 'Default evaluation contexts disabled'
} else if (updatedAttribute === 'require_evaluation_contexts') {
message = payload.require_evaluation_contexts
? 'Require evaluation contexts enabled'
: 'Require evaluation contexts disabled'
} else if (
updatedAttribute === 'completed_snippet_onboarding' ||
updatedAttribute === 'has_completed_onboarding_for'
) {
message = "Congrats! You're now ready to use PostHog."
} else {
message = `${parseUpdatedAttributeName(updatedAttribute)} updated successfully!`
}
Object.keys(payload).forEach((property) => {
posthog.capture(`${property} team setting updated`, {
setting: property,
value:
property === 'feature_flag_policy_config'
? featureFlagPolicyConfigForAnalytics(payload.feature_flag_policy_config)
: payload[property as keyof TeamType],
})
})
const isUpdatingOnboardingTasks = Object.keys(payload).every((key) => key === 'onboarding_tasks')
if (!window.location.pathname.match(/\/(onboarding|products)/) && !isUpdatingOnboardingTasks) {
lemonToast.success(message)
}
const setupLogic = globalSetupLogic.findMounted()
if (setupLogic) {
if (payload.autocapture_web_vitals_opt_in) {
setupLogic.actions.markTaskAsCompleted(SetupTaskId.SetUpWebVitals)
}
if (payload.session_recording_opt_in) {
setupLogic.actions.markTaskAsCompleted(SetupTaskId.SetupSessionRecordings)
}
if (payload.capture_console_log_opt_in) {
setupLogic.actions.markTaskAsCompleted(SetupTaskId.EnableConsoleLogs)
}
if (
payload.session_recording_sample_rate ||
payload.session_recording_minimum_duration_milliseconds ||
payload.session_recording_linked_flag ||
payload.session_recording_network_payload_capture_config
) {
setupLogic.actions.markTaskAsCompleted(SetupTaskId.ConfigureRecordingSettings)
}
}
return patchedTeam
},
createTeam: async ({ name, is_demo }: { name: string; is_demo: boolean }) => {
if (!values.currentProject) {
throw new Error(
'Environment could not be created, because the parent project has not been loaded yet!'
)
}
// 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.
return await api.create(`api/projects/${values.currentProject.id}/environments/`, { name, is_demo })
},
// Project API Token
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsResetTokenPartialUpdate() 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.
resetToken: async () => await api.update(`api/projects/${values.currentTeamId}/reset_token`, {}),
// Feature Flags Secure API Token
rotateSecretToken: async () =>
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsRotateSecretTokenPartialUpdate() 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.update(`api/projects/${values.currentTeamId}/rotate_secret_token`, {}),
deleteSecretTokenBackup: async () =>
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsDeleteSecretTokenBackupPartialUpdate() 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.update(`api/projects/${values.currentTeamId}/delete_secret_token_backup`, {}),
/**
* If adding a product intent that also represents regular product usage, see explainer in posthog.models.product_intent.product_intent.py.
*/
addProductIntent: async (properties: ProductIntentProperties) => {
const result = await addProductIntent(properties)
return withProductIntentsFrom(values.currentTeam, result)
},
addProductIntentForCrossSell: async (properties: ProductCrossSellProperties) => {
const result = await addProductIntentForCrossSell(properties)
return withProductIntentsFrom(values.currentTeam, result)
},
recordProductIntentOnboardingComplete: async (properties: ProductOnboardingCompleteProperties) => {
const result = await completeProductOnboarding(values.currentTeamIdStrict, properties)
return withProductIntentsFrom(values.currentTeam, result)
},
},
],
})),
selectors(() => ({
hasOnboardedAnyProduct: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): boolean => {
if (
currentTeam &&
!currentTeam.completed_snippet_onboarding &&
!Object.keys(currentTeam.has_completed_onboarding_for || {}).length
) {
return false
}
return true
},
],
currentTeamId: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): number | null => (currentTeam ? currentTeam.id : null),
],
// currentTeamIdStrict is currentTeamId with throwing an error to be consistent with the
// newly introduced currentProjectId and currentOrganizationId. To not cause a breaking change
// we kept currentTeamId as is for now. Ultimately throwing an error should be migrated to
// currentTeamId and so that currentTeamIdStrict can be removed.
currentTeamIdStrict: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): number | string => {
if (!currentTeam || !currentTeam.id) {
// TODO: Fix callers that access currentTeamIdStrict before the team is loaded,
// then restore the throw. Temporarily falling back to "@current" to avoid crashes.
posthog.captureException(new Error('currentTeamId accessed before team loaded'), {
severity: 'warning',
tag: 'selector_accessed_before_loaded',
})
return '@current'
}
return currentTeam.id
},
],
currentProjectId: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): number | string => {
if (!currentTeam || !currentTeam.project_id) {
// TODO: Fix callers that access currentProjectId before the team is loaded,
// then restore the throw. Temporarily falling back to "@current" to avoid crashes.
posthog.captureException(new Error('currentProjectId accessed before team loaded'), {
severity: 'warning',
tag: 'selector_accessed_before_loaded',
})
return '@current'
}
return currentTeam.project_id
},
],
isCurrentTeamUnavailable: [
(selectors) => [selectors.currentTeam, selectors.currentTeamLoading],
// If project has been loaded and is still null, it means the user just doesn't have access.
(currentTeam: TeamPublicType | TeamType | null, currentTeamLoading: boolean): boolean =>
(!currentTeam?.effective_membership_level || currentTeam.user_access_level === 'none') &&
!currentTeamLoading,
],
demoOnlyProject: [
(selectors) => [selectors.currentTeam, organizationLogic.selectors.currentOrganization],
(
currentTeam: TeamPublicType | TeamType | null,
currentOrganization: null | import('~/types').OrganizationType
): boolean =>
(currentTeam?.is_demo && currentOrganization?.teams && currentOrganization.teams.length == 1) || false,
],
timezone: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): string => currentTeam?.timezone || 'UTC',
],
/** 0 means Sunday, 1 means Monday. */
weekStartDay: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): number => currentTeam?.week_start_day || 0,
],
isTeamTokenResetAvailable: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): boolean =>
(!!currentTeam?.effective_membership_level &&
currentTeam.effective_membership_level >= OrganizationMembershipLevel.Admin) ||
currentTeam?.user_access_level === 'admin',
],
testAccountFilterFrequentMistakes: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamPublicType | TeamType | null): FrequentMistakeAdvice[] => {
if (!currentTeam) {
return []
}
const frequentMistakes: FrequentMistakeAdvice[] = []
for (const filter of currentTeam.test_account_filters || []) {
if (filter.key === 'email' && filter.type === 'event') {
frequentMistakes.push({
key: 'email',
type: 'event',
fix: 'it is more common to filter email by person properties, not event properties',
})
}
}
return frequentMistakes
},
],
baseCurrency: [
(selectors) => [selectors.currentTeam],
(currentTeam: TeamType): CurrencyCode => currentTeam?.base_currency ?? DEFAULT_CURRENCY,
],
customerAnalyticsConfig: [
(s) => [s.currentTeam],
(currentTeam: TeamType): CustomerAnalyticsConfig =>
currentTeam?.customer_analytics_config ?? ({} as CustomerAnalyticsConfig),
],
})),
listeners(({ actions, values }) => ({
loadCurrentTeamSuccess: ({ currentTeam }) => {
if (currentTeam) {
ApiConfig.setCurrentTeamId(currentTeam.id)
}
},
updateCurrentProjectSuccess: ({ currentProject, payload }) => {
if (payload && 'name' in payload && values.currentTeam?.project_id === currentProject.id) {
actions.loadCurrentTeamSuccess({ ...values.currentTeam, name: currentProject.name })
}
},
updateCurrentTeamSuccess: () => {
// Reload user after team update to keep user object in sync
actions.loadUser()
},
updateCurrentTeamFailure: ({ error, errorObject }: { error: string; errorObject?: unknown }) => {
const apiError = errorObject as ApiError | undefined
// The global loader handler drops 409s, on the assumption that each conflict flow
// renders its own. This one has none, so the rename would fail with nothing on screen.
if (apiError?.status === 409) {
lemonToast.error(apiError.detail || error)
}
},
createTeamSuccess: ({ currentTeam }) => {
if (currentTeam) {
actions.switchTeam(currentTeam.id)
}
},
deleteTeam: async ({ team }) => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. organizationsProjectsDestroy() 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/projects/${team.id}`)
location.reload()
actions.deleteTeamSuccess()
} catch {
actions.deleteTeamFailure()
}
},
deleteTeamSuccess: () => {
lemonToast.success('Project has been deleted')
},
})),
afterMount(({ actions }) => {
const appContext = getAppContext()
const currentTeam = appContext?.current_team
const switchedTeam = appContext?.switched_team
if (switchedTeam) {
lemonToast.info(<>You've switched to project {currentTeam?.name}</>, {
button: {
label: 'Switch back',
action: () => actions.switchTeam(switchedTeam),
},
icon: <IconSwapHoriz />,
})
// Clear the flag so a later remount of this logic does not re-announce the same switch.
if (appContext) {
appContext.switched_team = null
}
}
if (currentTeam) {
// If app context is available (it should be practically always) we can immediately know currentTeam
actions.loadCurrentTeamSuccess(currentTeam)
} else {
// If app context is not available, a traditional request is needed
actions.loadCurrentTeam()
}
}),
])