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.

35.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'

import { IconGear, IconPlus } from '@posthog/icons'

import api, { ApiError } from 'lib/api'
import { getProductPushDisplay } from 'lib/components/NavPanelAdvertisement/navPanelProductPushDisplay'
import { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { reverseProxyCheckerLogic } from 'lib/components/ReverseProxyChecker/reverseProxyCheckerLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonBannerProps } from 'lib/lemon-ui/LemonBanner/LemonBanner'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { Link } from 'lib/lemon-ui/Link'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { billingLogic, BillingAlertConfig } from 'lib/logic/billing/billingLogic'
import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { inviteLogic } from 'lib/logic/inviteLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { liveEventsLogic } from 'scenes/activity/live/liveEventsLogic'
import { verifyEmailLogic } from 'scenes/authentication/verify-email/verifyEmailLogic'
import { sampleDataStateLogic } from 'scenes/insights/EmptyStates/sampleDataStateLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { ProxyRecord } from 'scenes/settings/environment/proxyLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { brandingForProduct } from 'scenes/welcome/productBranding'

import { membersLogic } from '~/models/membersLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { OnboardingStepKey, TeamPublicType, TeamType, UserType } from '~/types'

import { EventIngestionRestrictionDetails } from './EventIngestionRestrictionDetails'
import { OrganizationMemberNoticeMessage } from './OrganizationMemberNoticeMessage'

export type ProjectNoticeVariant =
    | 'billing_alert'
    | 'demo_project'
    | 'provisioned_welcome'
    | 'real_project_with_no_events'
    | 'invite_teammates'
    | 'unverified_email'
    | 'internet_connection_issue'
    | 'event_ingestion_restriction'
    | 'missing_reverse_proxy'
    | 'organization_member_notice'

export interface ProjectNoticeBlueprint {
    message: JSX.Element | string
    action?: LemonBannerProps['action']
    type?: LemonBannerProps['type']
    onClose?: LemonBannerProps['onClose']
    mountNoEventsBannerLogic?: boolean
}

const NOTICE_DISMISS_PREFIX = 'project-notice-dismissed.'

// The products we want every provisioned account exploring. Keys resolve in both PRODUCT_BRANDING
// (label + docs) and PRODUCT_PUSH_DISPLAY (hog illustration), mirroring the welcome dialog's showcase.
const FLAGSHIP_PRODUCT_KEYS = [
    'product_analytics',
    'web_analytics',
    'session_replay',
    'error_tracking',
    'llm_analytics',
]

/** Compact row of flagship-product hogs + labels, echoing the welcome dialog inside the banner. */
function ProvisionedProductStrip(): JSX.Element {
    return (
        <span className="inline-flex flex-wrap items-center gap-x-3 gap-y-1 align-middle">
            {FLAGSHIP_PRODUCT_KEYS.map((productKey) => {
                const { Hoggie } = getProductPushDisplay(productKey)
                const meta = brandingForProduct(productKey)
                if (!Hoggie) {
                    return null
                }
                return (
                    <Link
                        key={productKey}
                        to={meta.docsHref}
                        target="_blank"
                        subtle
                        className="inline-flex items-center gap-1"
                        data-attr={`provisioned-welcome-${productKey}`}
                    >
                        <Hoggie className="h-6 w-auto" aria-hidden="true" />
                        <span className="text-xs font-medium">{meta.label}</span>
                    </Link>
                )
            })}
        </span>
    )
}

/** Message body of the provisioned-welcome banner. Exported so it's reviewable in Storybook. */
export function ProvisionedWelcomeMessage(): JSX.Element {
    return (
        <div className="flex flex-col gap-1">
            <span>
                <b>Welcome to PostHog!</b> We're setting up PostHog in your repo in the background. In the meantime,
                here's what you can do with it:
            </span>
            <ProvisionedProductStrip />
        </div>
    )
}

function isNoticeDismissed(key: string): boolean {
    try {
        return localStorage.getItem(NOTICE_DISMISS_PREFIX + key) === 'true'
    } catch {
        return false
    }
}

function storeNoticeDismissal(key: string): void {
    try {
        localStorage.setItem(NOTICE_DISMISS_PREFIX + key, 'true')
    } catch {
        /* noop */
    }
}

/**
 * Whether the missing-reverse-proxy notice could be eligible to show (and its data should be fetched).
 * Limited to the first 7 days of each month so the nudge stays noticeable without causing fatigue.
 * Requires an authenticated user and a loaded organization — otherwise the proxy_records GET fires
 * without a valid session and 401s, polluting error tracking with no banner to show anyway.
 */
function shouldFetchProxyRecords(user: UserType | null, currentOrganizationId: string | null): boolean {
    return !!user && !!currentOrganizationId && new Date().getDate() <= 7 && !isNoticeDismissed('missing_reverse_proxy')
}

function buildBillingAlertAction(
    billingAlert: BillingAlertConfig,
    canAccessBilling: boolean
): LemonBannerProps['action'] | undefined {
    if (billingAlert.action) {
        return billingAlert.action
    }

    if (billingAlert.contactSupport) {
        return {
            to: 'mailto:[email protected]',
            children: billingAlert.buttonCTA || 'Contact support',
            onClick: () => billingLogic.actions.reportBillingAlertActionClicked(billingAlert),
        }
    }

    if (!canAccessBilling) {
        return undefined
    }

    return {
        to: getBillingAlertBillingUrl(billingAlert),
        children: 'Manage billing',
        onClick: () => billingLogic.actions.reportBillingAlertActionClicked(billingAlert),
    }
}

function getBillingAlertBillingUrl(billingAlert: BillingAlertConfig): string {
    return urls.organizationBilling(billingAlert.productKey ? [billingAlert.productKey] : undefined)
}

function isBillingPathname(pathname: string): boolean {
    const billingPathname = urls.organizationBilling()

    return pathname === billingPathname || pathname.startsWith(`${billingPathname}/`)
}

function isCurrentBillingAlertBillingUrl(
    billingAlert: BillingAlertConfig,
    currentLocation: { pathname: string; searchParams: Record<string, any> }
): boolean {
    if (!isBillingPathname(currentLocation.pathname)) {
        return false
    }

    if (!billingAlert.productKey) {
        return true
    }

    const productsParam = currentLocation.searchParams.products
    const productKeys = Array.isArray(productsParam)
        ? productsParam
        : typeof productsParam === 'string'
          ? productsParam.split(',')
          : []

    return productKeys.includes(billingAlert.productKey)
}

function buildBillingAlertNotice(
    billingAlert: BillingAlertConfig,
    canAccessBilling: boolean,
    currentLocation: { pathname: string; searchParams: Record<string, any> }
): ProjectNoticeBlueprint {
    const showButton =
        billingAlert.action ||
        billingAlert.contactSupport ||
        !isCurrentBillingAlertBillingUrl(billingAlert, currentLocation)
    const action = buildBillingAlertAction(billingAlert, canAccessBilling)

    return {
        message: (
            <>
                <b>{billingAlert.title}</b>
                <br />
                {billingAlert.message}
            </>
        ),
        type: billingAlert.status,
        action: showButton ? action : undefined,
        onClose: billingAlert.onClose,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectNoticeLogicValues {
    effectiveBillingAlert: BillingAlertConfig | null // billingLogic
    memberCount: number // membersLogic
    currentOrganizationId: string // organizationLogic
    hasReverseProxy: boolean | null // reverseProxyCheckerLogic
    warehouseSetupStatus: ProductSetupStatus // sampleDataStateLogic
    user: UserType | null // userLogic
    noticeDismissedThisSession: boolean
    postHogNoticeVariant: ProjectNoticeVariant | null
    projectData: {
        currentTeam: TeamPublicType | TeamType | null
        warehouseSetupStatus: ProductSetupStatus
    }
    projectNotice: ProjectNoticeBlueprint | null
    projectNoticeDismissKey: string | null
    projectNoticeVariant: ProjectNoticeVariant | null
    proxyRecords: ProxyRecord[] | null
    proxyRecordsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectNoticeLogicActions {
    reportProjectNoticeDismissed: (key: string) => {
        key: string
    } // eventUsageLogic
    reportProjectNoticeShown: (variant: string) => {
        variant: string
    } // eventUsageLogic
    requestVerificationCode: (uuid: string) => {
        uuid: string
    } // verifyEmailLogic
    dismissProjectNotice: (dismissKey: string | null) => {
        dismissKey: string | null
    }
    loadRecords: () => any
    loadRecordsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRecordsSuccess: (
        proxyRecords: ProxyRecord[] | null,
        payload?: any
    ) => {
        proxyRecords: ProxyRecord[] | null
        payload?: any
    }
    reportNoticeShown: () => {
        value: true
    }
    showEventIngestionRestrictionDetails: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectNoticeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        projectData: (
            currentTeam: TeamPublicType | TeamType | null,
            warehouseSetupStatus: ProductSetupStatus
        ) => {
            currentTeam: TeamPublicType | TeamType | null
            warehouseSetupStatus: ProductSetupStatus
        }
        postHogNoticeVariant: (
            currentOrganization: null | import('~/types').OrganizationType,
            projectData: {
                currentTeam: TeamPublicType | TeamType | null
                warehouseSetupStatus: ProductSetupStatus
            },
            preflight: null | import('~/types').PreflightStatus,
            isCloudOrDev: boolean | undefined,
            user: UserType | null,
            memberCount: number,
            internetConnectionIssue: boolean,
            hasProjectNoticeRestriction: boolean,
            proxyRecords: import('products/platform_features/frontend/generated/api.schemas').ProxyRecordApi[] | null,
            effectiveBillingAlert: BillingAlertConfig | null,
            currentLocation: {
                hash: string
                hashParams: Record<string, any>
                method: string
                pathname: string
                search: string
                searchParams: Record<string, any>
            },
            noticeDismissedThisSession: boolean,
            activeSceneId: string | null,
            arg: number,
            hasReverseProxy: boolean | null,
            isProvisionedUser: boolean
        ) => ProjectNoticeVariant | null
        projectNoticeVariant: (
            postHogNoticeVariant: ProjectNoticeVariant | null,
            arg: boolean,
            arg2: boolean
        ) => ProjectNoticeVariant | null
        projectNoticeDismissKey: (
            projectNoticeVariant: ProjectNoticeVariant | null,
            effectiveBillingAlert: BillingAlertConfig | null
        ) => string | null
        projectNotice: (
            projectNoticeVariant: ProjectNoticeVariant | null,
            effectiveBillingAlert: BillingAlertConfig | null,
            projectNoticeDismissKey: string | null,
            currentOrganization: null | import('~/types').OrganizationType,
            user: UserType | null,
            canAccessBilling: boolean,
            currentLocation: {
                hash: string
                hashParams: Record<string, any>
                method: string
                pathname: string
                search: string
                searchParams: Record<string, any>
            },
            activeSceneProductKey: ProductKey | null
        ) => ProjectNoticeBlueprint | null
    }
}

export type projectNoticeLogicType = MakeLogicType<
    projectNoticeLogicValues,
    projectNoticeLogicActions,
    Record<string, any>,
    projectNoticeLogicMeta
>

export const projectNoticeLogic = kea<projectNoticeLogicType>([
    path(['layout', 'navigation', 'projectNoticeLogic']),
    connect(() => ({
        logic: [verifyEmailLogic, billingLogic],
        values: [
            membersLogic,
            ['memberCount'],
            organizationLogic,
            ['currentOrganizationId'],
            userLogic,
            ['user'],
            billingLogic,
            ['effectiveBillingAlert'],
            // Connecting reverseProxyCheckerLogic mounts it and exposes hasReverseProxy reactively.
            // A self-managed (DIY) reverse proxy never appears in proxy_records, but it does stamp
            // $lib_custom_api_host on events, which the checker detects — this keeps the "set up a
            // reverse proxy" nudge from contradicting the onboarding checklist, which marks the task
            // complete on the same signal. The checker throttles its own detection query internally.
            reverseProxyCheckerLogic,
            ['hasReverseProxy'],
            sampleDataStateLogic,
            ['warehouseSetupStatus'],
        ],
        actions: [
            eventUsageLogic,
            ['reportProjectNoticeDismissed', 'reportProjectNoticeShown'],
            // Mount verifyEmailLogic so the "Verify email" banner CTA's loader fires.
            // The banner renders on every scene, but verifyEmailLogic is otherwise only mounted on the verify-email scene.
            verifyEmailLogic,
            ['requestVerificationCode'],
        ],
    })),
    actions({
        dismissProjectNotice: (dismissKey: string | null) => ({ dismissKey }),
        reportNoticeShown: true,
        showEventIngestionRestrictionDetails: true,
    }),
    loaders(({ values }) => ({
        proxyRecords: {
            __default: null as null | ProxyRecord[],
            loadRecords: async () => {
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use proxyRecordsList() from 'products/platform_features/frontend/generated/api' instead.
                    const response = await api.get(`api/organizations/${values.currentOrganizationId}/proxy_records`)
                    return response.results
                } catch (error) {
                    // A missing or expired session makes this boot-time GET 401. A restricted org member
                    // whose access level to the org resource is below read gets a 403 from the RBAC layer.
                    // Either way there's no banner to show, so swallow it rather than polluting error tracking.
                    if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
                        return null
                    }
                    throw error
                }
            },
        },
    })),
    reducers({
        // Suppress all notices for the rest of the session after any dismiss
        noticeDismissedThisSession: [false, { dismissProjectNotice: () => true }],
    }),
    selectors({
        projectData: [
            (s) => [teamLogic.selectors.currentTeam, s.warehouseSetupStatus],
            (
                currentTeam: TeamPublicType | TeamType | null,
                warehouseSetupStatus: ProductSetupStatus
            ): { currentTeam: TeamPublicType | TeamType | null; warehouseSetupStatus: ProductSetupStatus } => ({
                currentTeam,
                warehouseSetupStatus,
            }),
        ],
        postHogNoticeVariant: [
            (s) => [
                organizationLogic.selectors.currentOrganization,
                s.projectData,
                preflightLogic.selectors.preflight,
                preflightLogic.selectors.isCloudOrDev,
                userLogic.selectors.user,
                s.memberCount,
                apiStatusLogic.selectors.internetConnectionIssue,
                eventIngestionRestrictionLogic.selectors.hasProjectNoticeRestriction,
                s.proxyRecords,
                s.effectiveBillingAlert,
                router.selectors.currentLocation,
                s.noticeDismissedThisSession,
                sceneLogic.selectors.activeSceneId,
                (state) => liveEventsLogic.findMounted()?.selectors.eventCount(state) ?? 0,
                // null = not yet checked; we only nudge once detection confirms there's no proxy.
                s.hasReverseProxy,
                userLogic.selectors.isProvisionedUser,
            ],
            (
                organization: null | import('~/types').OrganizationType,
                { currentTeam, warehouseSetupStatus }: projectNoticeLogicValues['projectData'],
                preflight: null | import('~/types').PreflightStatus,
                isCloudOrDev: boolean | undefined,
                user: UserType | null,
                memberCount: number,
                internetConnectionIssue: boolean,
                hasEventIngestionRestriction: boolean,
                proxyRecords: ProxyRecord[] | null,
                effectiveBillingAlert: BillingAlertConfig | null,
                currentLocation: {
                    hash: string
                    hashParams: Record<string, any>
                    method: string
                    pathname: string
                    search: string
                    searchParams: Record<string, any>
                },
                noticeDismissedThisSession: boolean,
                activeSceneId: string | null,
                liveEventCount: number,
                hasReverseProxy: boolean | null,
                isProvisionedUser: boolean
            ): ProjectNoticeVariant | null => {
                if (!organization) {
                    return null
                }

                if (noticeDismissedThisSession) {
                    return null
                }

                if (internetConnectionIssue) {
                    return 'internet_connection_issue'
                } else if (
                    effectiveBillingAlert &&
                    !(effectiveBillingAlert.pathName && currentLocation.pathname !== effectiveBillingAlert.pathName) &&
                    !(
                        effectiveBillingAlert.dismissKey &&
                        isNoticeDismissed(`billing_alert.${effectiveBillingAlert.dismissKey}`)
                    )
                ) {
                    return 'billing_alert'
                } else if (currentTeam?.is_demo && !preflight?.demo) {
                    // If the project is a demo one, show a project-level warning
                    // Don't show this project-level warning in the PostHog demo environemnt though,
                    // as then Announcement is shown instance-wide
                    return 'demo_project'
                } else if (!user?.is_email_verified && !user?.has_social_auth && preflight?.email_service_available) {
                    return 'unverified_email'
                } else if (isProvisionedUser && !isNoticeDismissed('provisioned_welcome')) {
                    // For partner-provisioned accounts, the welcome nudge supersedes the generic
                    // "no events yet" banner — their events arrive via the background wizard install.
                    return 'provisioned_welcome'
                } else if (
                    !isNoticeDismissed('real_project_with_no_events') &&
                    currentTeam &&
                    !currentTeam.ingested_event &&
                    warehouseSetupStatus === 'needs-setup' &&
                    // Belt-and-braces: never claim "no events" while the live activity feed is
                    // actively rendering events on the same screen — `currentTeam.ingested_event`
                    // can lag behind the live SSE stream during the first ingestion window.
                    !(activeSceneId === Scene.LiveEvents && liveEventCount > 0)
                ) {
                    return 'real_project_with_no_events'
                } else if (hasEventIngestionRestriction) {
                    return 'event_ingestion_restriction'
                } else if (
                    // Only show the reverse proxy nudge on Cloud (or dev) — self-hosted users
                    // control their own infrastructure and don't need managed proxies.
                    isCloudOrDev &&
                    shouldFetchProxyRecords(user, organization?.id ?? null) &&
                    proxyRecords !== null &&
                    proxyRecords.length === 0 &&
                    // ...and only once the checker has confirmed there's no self-managed proxy
                    // routing events. While it's still null (not yet checked) we hold the nudge
                    // back to avoid flashing it at DIY-proxy users before detection resolves.
                    hasReverseProxy === false
                ) {
                    return 'missing_reverse_proxy'
                } else if (!isNoticeDismissed('invite_teammates') && memberCount === 1) {
                    return 'invite_teammates'
                }

                return null
            },
        ],
        projectNoticeVariant: [
            (s) => [
                s.postHogNoticeVariant,
                (state) => !!organizationLogic.selectors.currentOrganization(state)?.member_notice?.message,
                (state) => !!featureFlagLogic.selectors.featureFlags(state)[FEATURE_FLAGS.UX_HIDE_PROJECT_NOTICE],
            ],
            (
                postHogNoticeVariant: ProjectNoticeVariant | null,
                hasMemberNotice: boolean,
                hidePostHogNotices: boolean
            ): ProjectNoticeVariant | null => {
                // The member notice comes last. Members can't dismiss it, and the flag only hides PostHog's notices.
                if (postHogNoticeVariant && !hidePostHogNotices) {
                    return postHogNoticeVariant
                }
                return hasMemberNotice ? 'organization_member_notice' : null
            },
        ],
        projectNoticeDismissKey: [
            (s) => [s.projectNoticeVariant, s.effectiveBillingAlert],
            (variant: ProjectNoticeVariant | null, effectiveBillingAlert: BillingAlertConfig | null): string | null => {
                switch (variant) {
                    case 'billing_alert':
                        return effectiveBillingAlert?.dismissKey
                            ? `billing_alert.${effectiveBillingAlert.dismissKey}`
                            : null
                    case 'real_project_with_no_events':
                    case 'missing_reverse_proxy':
                    case 'invite_teammates':
                    case 'provisioned_welcome':
                        return variant
                    default:
                        return null
                }
            },
        ],
        projectNotice: [
            (s) => [
                s.projectNoticeVariant,
                s.effectiveBillingAlert,
                s.projectNoticeDismissKey,
                organizationLogic.selectors.currentOrganization,
                userLogic.selectors.user,
                billingLogic.selectors.canAccessBilling,
                router.selectors.currentLocation,
                sceneLogic.selectors.activeSceneProductKey,
            ],
            (
                variant: ProjectNoticeVariant | null,
                effectiveBillingAlert: BillingAlertConfig | null,
                dismissKey: string | null,
                currentOrganization: null | import('~/types').OrganizationType,
                user: UserType | null,
                canAccessBilling: boolean,
                currentLocation: {
                    hash: string
                    hashParams: Record<string, any>
                    method: string
                    pathname: string
                    search: string
                    searchParams: Record<string, any>
                },
                activeSceneProductKey: ProductKey | null
            ): ProjectNoticeBlueprint | null => {
                if (!variant) {
                    return null
                }

                const dismiss = dismissKey
                    ? () => projectNoticeLogic.actions.dismissProjectNotice(dismissKey)
                    : undefined

                switch (variant) {
                    case 'billing_alert': {
                        if (!effectiveBillingAlert) {
                            return null
                        }
                        const notice = buildBillingAlertNotice(effectiveBillingAlert, canAccessBilling, currentLocation)
                        const canClose = dismiss || notice.onClose
                        return {
                            ...notice,
                            onClose: canClose
                                ? () => {
                                      notice.onClose?.()
                                      projectNoticeLogic.actions.dismissProjectNotice(dismissKey)
                                  }
                                : undefined,
                        }
                    }
                    case 'demo_project': {
                        const altTeam = currentOrganization?.teams?.find(
                            (team) => !team.is_demo && !team.ingested_event
                        )
                        return {
                            message: (
                                <>
                                    This is a demo project with dummy data.
                                    {altTeam && (
                                        <>
                                            {' '}
                                            When you're ready, head on over to the{' '}
                                            <Link
                                                to={urls.project(altTeam.id, urls.onboarding())}
                                                data-attr="demo-project-alt-team-ingestion_link"
                                            >
                                                onboarding flow
                                            </Link>{' '}
                                            to get started with your own data.
                                        </>
                                    )}
                                </>
                            ),
                        }
                    }
                    case 'real_project_with_no_events':
                        return {
                            message: (
                                <>
                                    This project has no events yet. Go to the{' '}
                                    <Link
                                        to={urls.onboarding({
                                            productKey: activeSceneProductKey ?? ProductKey.PRODUCT_ANALYTICS,
                                            stepKey: OnboardingStepKey.INSTALL,
                                        })}
                                        data-attr="real_project_with_no_events-ingestion_link"
                                    >
                                        onboarding flow
                                    </Link>{' '}
                                    or grab your project API key/HTML snippet from{' '}
                                    <Link
                                        to={urls.settings('project-details', 'variables')}
                                        data-attr="real_project_with_no_events-settings"
                                    >
                                        Project Settings
                                    </Link>{' '}
                                    to get things moving
                                </>
                            ),
                            action: {
                                to: urls.onboarding({
                                    productKey: activeSceneProductKey ?? ProductKey.PRODUCT_ANALYTICS,
                                    stepKey: OnboardingStepKey.INSTALL,
                                }),
                                'data-attr': 'demo-warning-cta',
                                icon: <IconGear />,
                                children: 'Go to onboarding',
                            },
                            onClose: dismiss,
                            mountNoEventsBannerLogic: true,
                        }
                    case 'provisioned_welcome':
                        return {
                            message: <ProvisionedWelcomeMessage />,
                            type: 'info',
                            onClose: dismiss,
                        }
                    case 'invite_teammates':
                        return {
                            message: 'Get more out of PostHog by inviting your team for free',
                            action: {
                                'data-attr': 'invite-warning-cta',
                                onClick: () => inviteLogic.actions.showInviteModal(),
                                icon: <IconPlus />,
                                children: 'Invite team members',
                            },
                            onClose: dismiss,
                        }
                    case 'unverified_email':
                        return {
                            message: 'Please verify your email address.',
                            action: {
                                'data-attr': 'unverified-email-cta',
                                onClick: () => {
                                    if (!user) {
                                        return
                                    }
                                    verifyEmailLogic.actions.requestVerificationCode(user.uuid)
                                    // The email carries a 6-digit code, and only the verify-email scene has the
                                    // entry form. `next` returns the user to this page once the code is accepted.
                                    const { pathname, search, hash } = router.values.location
                                    router.actions.push(urls.verifyEmail(user.uuid), { next: pathname + search + hash })
                                },
                                children: 'Verify email',
                            },
                            type: 'warning',
                        }
                    case 'internet_connection_issue':
                        return {
                            message:
                                'PostHog is having trouble connecting to the server. Please check your connection.',
                            type: 'warning',
                            action: {
                                'data-attr': 'reload-page',
                                onClick: () => window.location.reload(),
                                children: 'Reload page',
                            },
                        }
                    case 'event_ingestion_restriction':
                        return {
                            message:
                                'Event ingestion restrictions have been applied to a token in this project. Please contact support.',
                            type: 'warning',
                            action: {
                                onClick: () => projectNoticeLogic.actions.showEventIngestionRestrictionDetails(),
                                'data-attr': 'event-ingestion-restriction-details_link',
                                children: 'See details',
                            },
                        }
                    case 'missing_reverse_proxy':
                        return {
                            message:
                                'Ad blockers can silently drop 10-25% of your events. Set up a reverse proxy to route data through your own domain and prevent this.',
                            type: 'info',
                            action: {
                                to: urls.settings('organization-proxy'),
                                'data-attr': 'missing-reverse-proxy-settings_link',
                                icon: <IconGear />,
                                children: 'Set up reverse proxy',
                            },
                            onClose: dismiss,
                        }
                    case 'organization_member_notice': {
                        const memberNotice = currentOrganization?.member_notice
                        if (!memberNotice) {
                            return null
                        }
                        return {
                            message: <OrganizationMemberNoticeMessage html={memberNotice.message} />,
                            type: 'info',
                            action: memberNotice.action
                                ? {
                                      to: memberNotice.action.url,
                                      targetBlank: true,
                                      children: memberNotice.action.label,
                                      'data-attr': 'organization-member-notice-action',
                                  }
                                : undefined,
                        }
                    }
                    default:
                        return null
                }
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        showEventIngestionRestrictionDetails: () => {
            LemonDialog.open({
                title: 'Event ingestion restrictions',
                content: (
                    <EventIngestionRestrictionDetails
                        restrictions={eventIngestionRestrictionLogic.values.eventIngestionRestrictions}
                    />
                ),
                primaryButton: { children: 'Close' },
                width: 560,
            })
        },
        dismissProjectNotice: ({ dismissKey }) => {
            if (dismissKey) {
                storeNoticeDismissal(dismissKey)
            }
            actions.reportProjectNoticeDismissed(dismissKey ?? values.projectNoticeVariant ?? 'unknown')
        },
        reportNoticeShown: () => {
            if (values.projectNoticeVariant) {
                actions.reportProjectNoticeShown(values.projectNoticeVariant)
            }
            if (values.projectNoticeVariant === 'billing_alert' && values.effectiveBillingAlert) {
                billingLogic.actions.reportBillingAlertShown(values.effectiveBillingAlert)
            }
        },
    })),
    afterMount(({ actions, values }) => {
        if (shouldFetchProxyRecords(values.user, values.currentOrganizationId)) {
            actions.loadRecords()
        }
    }),
])