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.

89.0 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { FieldNamePath, capitalizeFirstLetter, forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { lazyLoaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import { LemonDialog, Link, lemonToast } from '@posthog/lemon-ui'

import api, { getJSONOrNull } from 'lib/api'
import { buildFakeBillingAlert } from 'lib/components/Superpowers/buildFakeBillingAlert'
import { FakeBillingAlert, superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
import { getSupportResponseTime } from 'lib/components/Support/supportResponseTime'
import { FEATURE_FLAGS, FeatureFlagKey, OrganizationMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { LemonBannerAction } from 'lib/lemon-ui/LemonBanner/LemonBanner'
import { lemonBannerLogic } from 'lib/lemon-ui/LemonBanner/lemonBannerLogic'
import { LemonButtonPropsBase } from 'lib/lemon-ui/LemonButton'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { sceneRenderedLogic } from 'lib/logic/sceneRenderedLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { pluralize } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { ProductKey } from '~/queries/schema/schema-general'
import {
    BillingPeriod,
    BillingPlan,
    BillingPlanType,
    BillingProductV2AddonType,
    BillingProductV2Type,
    BillingProvider,
    BillingType,
    OrganizationType,
    PreflightStatus,
    StartupProgramLabel,
} from '~/types'

import {
    canAccessBilling as canAccessBillingUtil,
    canViewUsageAndSpend as canViewUsageAndSpendUtil,
    getMinimumBillingAccessLevel,
    getMinimumUsageSpendReadAccessLevel,
    isMemberUsageSpendReadAccessEnabled,
} from './billingAccess'
import { isCompanionProduct } from './companionProducts'
import { eventsRetentionMonths } from './eventsRetentionMonths'
import {
    buildUsageLimitApproachingMessage,
    buildUsageLimitReachedMessage,
    isUsageApproachingLimit,
    isUsageAtOrOverLimit,
} from './usageLimits'

export const DEFAULT_ESTIMATED_MONTHLY_CREDIT_AMOUNT_USD = 500

// in sync with GRANDFATHERED_EVENTS_RETENTION_PLAN in billing
export const GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY = 'paid-20240404'

export const ALLOCATION_THRESHOLD_ALERT = 0.8 // Threshold to show warning of event usage near limit (aligned with the 80% billing warning email)
export const ALLOCATION_THRESHOLD_BLOCK = 1.2 // Threshold to block usage

const BILLING_ALERT_DISMISS_PREFIX = 'scenes.billing.billingLogic.billingAlertDismissed.'

const getFirstProductFromProductsParam = (productsParam: unknown): ProductKey | null => {
    if (typeof productsParam !== 'string') {
        return null
    }

    const [product] = productsParam.split(',')
    return product ? (product as ProductKey) : null
}

export interface BillingAlertConfig {
    kind?: 'trial' | 'usage_limit'
    status: 'info' | 'warning' | 'error'
    title: string
    message?: string
    contactSupport?: boolean
    buttonCTA?: string
    dismissKey?: string
    productKey?: ProductKey
    action?: LemonBannerAction
    pathName?: string
    onClose?: () => void
}

const isManagedBillingAlert = (billingAlert: BillingAlertConfig | null): boolean => billingAlert?.kind !== undefined

export enum BillingAPIErrorCodes {
    OPEN_INVOICES_ERROR = 'open_invoices_error',
    NO_ACTIVE_PAYMENT_METHOD_ERROR = 'no_active_payment_method_error',
    COULD_NOT_PAY_INVOICES_ERROR = 'could_not_pay_invoices_error',
}

export interface UnsubscribeError {
    detail: string | JSX.Element
    link: JSX.Element
}

export interface BillingError {
    status: 'info' | 'warning' | 'error'
    message: string
    action: LemonButtonPropsBase
}

export interface OpenInvoices {
    count: number
    link: string | null
}

export type SwitchPlanPayload = {
    from_product_key: string
    from_plan_key: string
    to_product_key: string
    to_plan_key: string
}

/**
 * renewing: credits left, and they renew every year
 * used_until_renewal: no credits left until the next yearly renewal
 * ending: credits left, but they do not renew
 * ended: no credits left, and they do not renew
 */
export type YcCreditsState = 'renewing' | 'used_until_renewal' | 'ending' | 'ended'

// Billing can answer with an empty body (a proxy error page, an upstream failure), so this takes null.
export const parseBillingResponse = (data: Partial<BillingType> | null): BillingType | null => {
    if (!data) {
        return null
    }
    if (data.billing_period) {
        data.billing_period = {
            current_period_start: dayjs(data.billing_period.current_period_start),
            current_period_end: dayjs(data.billing_period.current_period_end),
            interval: data.billing_period.interval,
        }
    }

    data.free_trial_until = data.free_trial_until ? dayjs(data.free_trial_until) : undefined
    data.amount_off_expires_at = data.amount_off_expires_at ? dayjs(data.amount_off_expires_at) : undefined
    // If expiration is in the middle of the current period, we let it expire at the end of the period.
    // YC credits are the exception: billing renews or ends them on the expiry date itself.
    if (
        data.startup_program_label !== StartupProgramLabel.YC &&
        data.amount_off_expires_at &&
        data.billing_period &&
        data.amount_off_expires_at.isBefore(data.billing_period.current_period_end) &&
        data.amount_off_expires_at.isAfter(data.billing_period.current_period_start)
    ) {
        data.amount_off_expires_at = data.billing_period.current_period_end
    }

    return data as BillingType
}

const storeBillingAlertDismissal = (
    organizationId: string | undefined,
    productType: string,
    billingPeriodEnd: string | null | undefined,
    suffix: string = ''
): void => {
    if (billingPeriodEnd && organizationId) {
        try {
            const dismissKey = `${BILLING_ALERT_DISMISS_PREFIX}${organizationId}.${productType}${suffix}`
            localStorage.setItem(dismissKey, billingPeriodEnd)
        } catch (error) {
            // localStorage not available, continue without storing
            console.warn('localStorage not available for billing alert dismissal:', error)
        }
    }
}

const isBillingAlertDismissed = (
    organizationId: string | undefined,
    productType: string,
    billingPeriodEnd: string | null | undefined,
    suffix: string = ''
): boolean => {
    if (!billingPeriodEnd || !organizationId) {
        return false
    }

    try {
        const dismissKey = `${BILLING_ALERT_DISMISS_PREFIX}${organizationId}.${productType}${suffix}`
        const dismissedData = localStorage.getItem(dismissKey)

        if (dismissedData) {
            // If the stored billing period end is different from current, remove the key and show the alert
            if (dismissedData !== billingPeriodEnd) {
                localStorage.removeItem(dismissKey)
                return false
            }
            // Alert was dismissed for this period, don't show it
            return true
        }
        return false
    } catch (error) {
        // localStorage not available, continue to show alert
        console.warn('localStorage not available for billing alert dismissal:', error)
        return false
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface billingLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    currentOrganization: OrganizationType | null // organizationLogic
    currentOrganizationId: string // organizationLogic
    preflight: PreflightStatus | null // preflightLogic
    sceneHasRendered: boolean // sceneRenderedLogic
    fakeBillingAlert: FakeBillingAlert // superpowersLogic
    accountOwner: {
        email?: string
        name?: string
    } | null
    activateLicense: {
        license: string
    }
    activateLicenseAllErrors: Record<string, any>
    activateLicenseChanged: boolean
    activateLicenseErrors: DeepPartialMap<
        {
            license: string
        },
        ValidationErrorType
    >
    activateLicenseHasErrors: boolean
    activateLicenseManualErrors: Record<string, any>
    activateLicenseTouched: boolean
    activateLicenseTouches: Record<string, boolean>
    activateLicenseValidationErrors: DeepPartialMap<
        {
            license: string
        },
        ValidationErrorType
    >
    billing: BillingType | null
    billingAlert: BillingAlertConfig | null
    billingEntryUrl: string | null
    billingError: BillingError | null
    billingLoading: boolean
    billingManagedByPartnerDisabledReason: string | null
    billingManagedByPartnerNotice: string | null
    billingManagedByVercelDisabledReason: string | null
    billingManagedByVercelNotice: string | null
    billingPeriodUTC: BillingPeriod
    billingPlan: BillingPlan | null
    canAccessBilling: boolean
    canOnlyViewUsageAndSpend: boolean
    canViewUsageAndSpend: boolean
    computedDiscount: number | null
    creditBrackets: any[]
    creditDiscount: number
    creditForm: {
        collectionMethod: string
        creditInput: string
    }
    creditFormAllErrors: Record<string, any>
    creditFormChanged: boolean
    creditFormErrors: DeepPartialMap<
        {
            collectionMethod: string
            creditInput: string
        },
        ValidationErrorType
    >
    creditFormHasErrors: boolean
    creditFormManualErrors: Record<string, any>
    creditFormTouched: boolean
    creditFormTouches: Record<string, boolean>
    creditFormValidationErrors: DeepPartialMap<
        {
            collectionMethod: string
            creditInput: string
        },
        ValidationErrorType
    >
    creditOverview: {
        cc_last_four: null
        collection_method: null
        credit_brackets: never[]
        eligible: false
        email: null
        estimated_monthly_credit_amount_usd: null
        invoice_url: null
        status: string
    }
    creditOverviewLoading: boolean
    currentEventsRetentionMonths: number | null
    currentPlatformAddon: BillingProductV2AddonType | null
    currentPlatformAddonPlan: BillingPlanType | null
    effectiveBillingAlert: BillingAlertConfig | null
    estimatedMonthlyCreditAmountUsd: number | null
    hasGrandfatheredEventsRetention: boolean
    hasSupportAddonPlan: boolean
    isActivateLicenseSubmitting: boolean
    isActivateLicenseValid: boolean
    isAnnualPlanCustomer: boolean
    isBillingManagedByPartner: boolean
    isBillingManagedByVercel: boolean
    isCreditCTAHeroDismissed: boolean
    isCreditFormSubmitting: boolean
    isCreditFormValid: boolean
    isExternallyBilled: boolean
    isManagedAccount: boolean
    isOnboarding: boolean
    isProductAtOrOverUsageLimit: (productKey: ProductKey) => boolean
    isPurchaseCreditsModalOpen: boolean
    isUnlicensedDebug: boolean
    minimumBillingAccessLevel: OrganizationMembershipLevel
    minimumUsageSpendReadAccessLevel: OrganizationMembershipLevel
    openInvoices: OpenInvoices | null
    openInvoicesLoading: boolean
    platformAddons: BillingProductV2AddonType[]
    productAnalyticsFreePlan: BillingPlanType | null
    productAnalyticsPlanAfterPackageDowngrade: BillingPlanType | null
    productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
    productAnalyticsPlans: BillingPlanType[]
    productSpecificAlert: BillingAlertConfig | null
    products: BillingProductV2Type[]
    productsLoading: boolean
    redirectPath: string
    registeredCustomLimitKeys: string[]
    scrollToProductKey: ProductKey | null
    selfServeBillingDisabledReason: string | null
    selfServeBillingNotice: string | null
    showActivateLicenseErrors: boolean
    showBillingHero: boolean
    showBillingSummary: boolean
    showCreditCTAHero: boolean
    showCreditFormErrors: boolean
    showLicenseDirectInput: boolean
    startupProgramLabelCurrent: StartupProgramLabel | null
    startupProgramLabelPrevious: StartupProgramLabel | null
    supportPlans: BillingPlanType[]
    supportResponseTime: string | null
    switchPlanLoading: string | null
    timeRemainingInSeconds: number
    timeTotalInSeconds: number
    unsubscribeError: UnsubscribeError | null
    unusedPlatformAddonAmount: number
    upgradeLink: string
    ycCreditsState: YcCreditsState | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface billingLogicActions {
    reportProductUnsubscribed: (product: string) => {
        product: string
    } // eventUsageLogic
    resetUsageLimitApproachingKey: () => {
        value: true
    } // lemonBannerLogic
    resetUsageLimitExceededKey: () => {
        value: true
    } // lemonBannerLogic
    loadCurrentOrganization: () => any // organizationLogic
    sceneRendered: () => {
        value: true
    } // sceneRenderedLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    deactivateProduct: (key: string) => string
    deactivateProductFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deactivateProductSuccess: (
        billing: BillingType | null,
        payload?: string
    ) => {
        billing: BillingType | null
        payload?: string
    }
    determineBillingAlert: () => {
        value: true
    }
    loadBilling: () => any
    loadBillingFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadBillingSuccess: (
        billing: BillingType | null,
        payload?: any
    ) => {
        billing: BillingType | null
        payload?: any
    }
    loadCreditOverview: () => any
    loadCreditOverviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCreditOverviewSuccess: (
        creditOverview: {
            cc_last_four: null
            collection_method: null
            credit_brackets: never[]
            eligible: false
            email: null
            estimated_monthly_credit_amount_usd: null
            invoice_url: null
            status: string
        },
        payload?: any
    ) => {
        creditOverview: {
            cc_last_four: null
            collection_method: null
            credit_brackets: never[]
            eligible: false
            email: null
            estimated_monthly_credit_amount_usd: null
            invoice_url: null
            status: string
        }
        payload?: any
    }
    loadInvoices: () => any
    loadInvoicesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInvoicesSuccess: (
        openInvoices: OpenInvoices | null,
        payload?: any
    ) => {
        openInvoices: OpenInvoices | null
        payload?: any
    }
    loadProducts: () => any
    loadProductsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadProductsSuccess: (
        products: BillingProductV2Type[],
        payload?: any
    ) => {
        products: BillingProductV2Type[]
        payload?: any
    }
    registerInstrumentationProps: () => {
        value: true
    }
    reportBillingAlertActionClicked: (alertConfig: BillingAlertConfig) => {
        alertConfig: BillingAlertConfig
    }
    reportBillingAlertShown: (alertConfig: BillingAlertConfig) => {
        alertConfig: BillingAlertConfig
    }
    reportBillingShown: () => {
        value: true
    }
    reportCreditsCTAShown: (creditOverview: any) => {
        creditOverview: any
    }
    reportCreditsFormSubmitted: (creditInput: number) => {
        creditInput: number
    }
    reportCreditsModalShown: () => {
        value: true
    }
    resetActivateLicense: (values?: { license: string }) => {
        values?: {
            license: string
        }
    }
    resetCreditForm: (values?: { collectionMethod: string; creditInput: string }) => {
        values?: {
            collectionMethod: string
            creditInput: string
        }
    }
    resetUnsubscribeError: () => {
        value: true
    }
    scrollToProduct: (productType: string) => {
        productType: string
    }
    setActivateLicenseManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setActivateLicenseValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setActivateLicenseValues: (
        values: DeepPartial<{
            license: string
        }>
    ) => {
        values: DeepPartial<{
            license: string
        }>
    }
    setBillingAlert: (billingAlert: BillingAlertConfig | null) => {
        billingAlert: BillingAlertConfig | null
    }
    setComputedDiscount: (discount: number) => {
        discount: number
    }
    setCreditBrackets: (creditBrackets: any[]) => {
        creditBrackets: any[]
    }
    setCreditFormManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setCreditFormValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setCreditFormValues: (
        values: DeepPartial<{
            collectionMethod: string
            creditInput: string
        }>
    ) => {
        values: DeepPartial<{
            collectionMethod: string
            creditInput: string
        }>
    }
    setIsOnboarding: (isOnboarding: boolean) => {
        isOnboarding: boolean
    }
    setProductSpecificAlert: (productSpecificAlert: BillingAlertConfig | null) => {
        productSpecificAlert: BillingAlertConfig | null
    }
    setRedirectPath: (redirectPath: string) => {
        redirectPath: string
    }
    setRegisteredCustomLimitKeys: (keys: string[]) => {
        keys: string[]
    }
    setScrollToProductKey: (scrollToProductKey: ProductKey | null) => {
        scrollToProductKey: ProductKey | null
    }
    setShowLicenseDirectInput: (show: boolean) => {
        show: boolean
    }
    setSwitchPlanLoading: (productKey: string | null) => {
        productKey: string | null
    }
    setUnsubscribeError: (error: UnsubscribeError | null) => {
        error: UnsubscribeError | null
    }
    showPurchaseCreditsModal: (isOpen: boolean) => {
        isOpen: boolean
    }
    submitActivateLicense: () => {
        value: boolean
    }
    submitActivateLicenseFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitActivateLicenseRequest: (activateLicense: { license: string }) => {
        activateLicense: {
            license: string
        }
    }
    submitActivateLicenseSuccess: (activateLicense: { license: string }) => {
        activateLicense: {
            license: string
        }
    }
    submitCreditForm: () => {
        value: boolean
    }
    submitCreditFormFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitCreditFormRequest: (creditForm: { collectionMethod: string; creditInput: string }) => {
        creditForm: {
            collectionMethod: string
            creditInput: string
        }
    }
    submitCreditFormSuccess: (creditForm: { collectionMethod: string; creditInput: string }) => {
        creditForm: {
            collectionMethod: string
            creditInput: string
        }
    }
    switchFlatrateSubscriptionPlan: (data: SwitchPlanPayload) => SwitchPlanPayload
    switchFlatrateSubscriptionPlanFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    switchFlatrateSubscriptionPlanSuccess: (
        billing: BillingType,
        payload?: SwitchPlanPayload
    ) => {
        billing: BillingType
        payload?: SwitchPlanPayload
    }
    toggleCreditCTAHeroDismissed: (isDismissed: boolean) => {
        isDismissed: boolean
    }
    touchActivateLicenseField: (key: string) => {
        key: string
    }
    touchCreditFormField: (key: string) => {
        key: string
    }
    updateBillingLimits: (limits: { [key: string]: number | null }) => {
        [key: string]: number | null
    }
    updateBillingLimitsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateBillingLimitsSuccess: (
        billing: BillingType | null,
        payload?: {
            [key: string]: number | null
        }
    ) => {
        billing: BillingType | null
        payload?: {
            [key: string]: number | null
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface billingLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        effectiveBillingAlert: (
            billingAlert: BillingAlertConfig | null,
            fakeBillingAlert: FakeBillingAlert
        ) => BillingAlertConfig | null
        minimumBillingAccessLevel: (featureFlags: FeatureFlagsSet) => OrganizationMembershipLevel
        canAccessBilling: (currentOrganization: OrganizationType | null, featureFlags: FeatureFlagsSet) => boolean
        minimumUsageSpendReadAccessLevel: (featureFlags: FeatureFlagsSet) => OrganizationMembershipLevel
        canViewUsageAndSpend: (currentOrganization: OrganizationType | null, featureFlags: FeatureFlagsSet) => boolean
        canOnlyViewUsageAndSpend: (canViewUsageAndSpend: boolean, canAccessBilling: boolean) => boolean
        billingEntryUrl: (canAccessBilling: boolean, canOnlyViewUsageAndSpend: boolean) => string | null
        upgradeLink: (preflight: PreflightStatus | null) => string
        isUnlicensedDebug: (preflight: PreflightStatus | null, billing: BillingType | null) => boolean
        supportPlans: (billing: BillingType | null) => BillingPlanType[]
        hasSupportAddonPlan: (billing: BillingType | null) => boolean
        platformAddons: (billing: BillingType | null) => BillingProductV2AddonType[]
        currentPlatformAddon: (billing: BillingType | null) => BillingProductV2AddonType | null
        currentPlatformAddonPlan: (currentPlatformAddon: BillingProductV2AddonType | null) => BillingPlanType | null
        productAnalyticsPlans: (billing: BillingType | null) => BillingPlanType[]
        productAnalyticsFreePlan: (productAnalyticsPlans: BillingPlanType[]) => BillingPlanType | null
        productAnalyticsPlanReplacingGrandfathered: (productAnalyticsPlans: BillingPlanType[]) => BillingPlanType | null
        hasGrandfatheredEventsRetention: (
            productAnalyticsPlans: BillingPlanType[],
            productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
        ) => boolean
        productAnalyticsPlanAfterPackageDowngrade: (
            productAnalyticsPlans: BillingPlanType[],
            hasGrandfatheredEventsRetention: boolean,
            productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
        ) => BillingPlanType | null
        currentEventsRetentionMonths: (currentOrganization: OrganizationType | null) => number | null
        unusedPlatformAddonAmount: (
            currentPlatformAddon: BillingProductV2AddonType | null,
            timeRemainingInSeconds: number,
            timeTotalInSeconds: number
        ) => number
        creditDiscount: (computedDiscount: number | null) => number
        billingPlan: (billing: BillingType | null) => BillingPlan | null
        supportResponseTime: (
            billing: BillingType | null,
            billingPlan: BillingPlan | null,
            supportPlans: BillingPlanType[],
            currentOrganization: OrganizationType | null
        ) => string | null
        startupProgramLabelCurrent: (billing: BillingType | null) => StartupProgramLabel | null
        startupProgramLabelPrevious: (billing: BillingType | null) => StartupProgramLabel | null
        ycCreditsState: (billing: BillingType | null) => YcCreditsState | null
        isAnnualPlanCustomer: (billing: BillingType | null) => boolean
        isProductAtOrOverUsageLimit: (billing: BillingType | null) => (productKey: ProductKey) => boolean
        billingPeriodUTC: (billing: BillingType | null) => BillingPeriod
        showBillingSummary: (billing: BillingType | null, isOnboarding: boolean) => boolean
        isBillingManagedByPartner: (billing: BillingType | null) => boolean
        billingManagedByPartnerDisabledReason: (billing: BillingType | null) => string | null
        billingManagedByPartnerNotice: (billingManagedByPartnerDisabledReason: string | null) => string | null
        isBillingManagedByVercel: (billing: BillingType | null) => boolean
        billingManagedByVercelDisabledReason: (
            billing: BillingType | null,
            isBillingManagedByVercel: boolean
        ) => string | null
        billingManagedByVercelNotice: (
            isBillingManagedByVercel: boolean,
            billingManagedByVercelDisabledReason: string | null
        ) => string | null
        selfServeBillingDisabledReason: (
            billingManagedByPartnerDisabledReason: string | null,
            billingManagedByVercelDisabledReason: string | null
        ) => string | null
        selfServeBillingNotice: (
            billingManagedByPartnerNotice: string | null,
            billingManagedByVercelDisabledReason: string | null
        ) => string | null
        showCreditCTAHero: (
            creditOverview: {
                cc_last_four: null
                collection_method: null
                credit_brackets: never[]
                eligible: false
                email: null
                estimated_monthly_credit_amount_usd: null
                invoice_url: null
                status: string
            },
            isBillingManagedByPartner: boolean
        ) => boolean
        showBillingHero: (
            billing: BillingType | null,
            billingPlan: BillingPlan | null,
            showCreditCTAHero: boolean,
            selfServeBillingDisabledReason: string | null
        ) => boolean
        isManagedAccount: (billing: BillingType | null) => boolean
        isExternallyBilled: (billing: BillingType | null) => boolean
        billingError: (
            openInvoices: OpenInvoices | null,
            billing: BillingType | null,
            isExternallyBilled: boolean
        ) => BillingError | null
        accountOwner: (billing: BillingType | null) => {
            email?: string
            name?: string
        } | null
        estimatedMonthlyCreditAmountUsd: (creditOverview: {
            cc_last_four: null
            collection_method: null
            credit_brackets: never[]
            eligible: false
            email: null
            estimated_monthly_credit_amount_usd: null
            invoice_url: null
            status: string
        }) => number | null
    }
}

export type billingLogicType = MakeLogicType<
    billingLogicValues,
    billingLogicActions,
    Record<string, any>,
    billingLogicMeta
>

export const billingLogic = kea<billingLogicType>([
    // pinned: the persisted isCreditCTAHeroDismissed reducer derives its localStorage key from this path
    path(['scenes', 'billing', 'billingLogic']),
    actions({
        setProductSpecificAlert: (productSpecificAlert: BillingAlertConfig | null) => ({ productSpecificAlert }),
        setScrollToProductKey: (scrollToProductKey: ProductKey | null) => ({ scrollToProductKey }),
        setShowLicenseDirectInput: (show: boolean) => ({ show }),
        reportBillingAlertShown: (alertConfig: BillingAlertConfig) => ({ alertConfig }),
        reportBillingAlertActionClicked: (alertConfig: BillingAlertConfig) => ({ alertConfig }),
        reportCreditsFormSubmitted: (creditInput: number) => ({ creditInput }),
        reportCreditsModalShown: true,
        reportBillingShown: true,
        registerInstrumentationProps: true,
        reportCreditsCTAShown: (creditOverview: any) => ({ creditOverview }),
        setRedirectPath: (redirectPath: string) => ({ redirectPath }),
        setIsOnboarding: (isOnboarding: boolean) => ({ isOnboarding }),
        determineBillingAlert: true,
        setUnsubscribeError: (error: null | UnsubscribeError) => ({ error }),
        resetUnsubscribeError: true,
        setBillingAlert: (billingAlert: BillingAlertConfig | null) => ({ billingAlert }),
        showPurchaseCreditsModal: (isOpen: boolean) => ({ isOpen }),
        toggleCreditCTAHeroDismissed: (isDismissed: boolean) => ({ isDismissed }),
        setComputedDiscount: (discount: number) => ({ discount }),
        setCreditBrackets: (creditBrackets: any[]) => ({ creditBrackets }),
        setRegisteredCustomLimitKeys: (keys: string[]) => ({ keys }),
        scrollToProduct: (productType: string) => ({ productType }),
        setSwitchPlanLoading: (productKey: string | null) => ({ productKey }),
    }),
    connect(() => ({
        values: [
            featureFlagLogic,
            ['featureFlags'],
            preflightLogic,
            ['preflight'],
            organizationLogic,
            ['currentOrganization', 'currentOrganizationId'],
            superpowersLogic,
            ['fakeBillingAlert'],
            sceneRenderedLogic,
            ['sceneHasRendered'],
        ],
        actions: [
            sceneRenderedLogic,
            ['sceneRendered'],
            userLogic,
            ['loadUser'],
            organizationLogic,
            ['loadCurrentOrganization'],
            eventUsageLogic,
            ['reportProductUnsubscribed'],
            lemonBannerLogic({ dismissKey: 'usage-limit-exceeded' }),
            ['resetDismissKey as resetUsageLimitExceededKey'],
            lemonBannerLogic({ dismissKey: 'usage-limit-approaching' }),
            ['resetDismissKey as resetUsageLimitApproachingKey'],
        ],
    })),
    reducers({
        billingAlert: [
            null as BillingAlertConfig | null,
            {
                setBillingAlert: (_, { billingAlert }) => billingAlert,
            },
        ],
        registeredCustomLimitKeys: [
            [] as string[],
            {
                setRegisteredCustomLimitKeys: (_, { keys }) => keys,
            },
        ],
        scrollToProductKey: [
            null as ProductKey | null,
            {
                setScrollToProductKey: (_, { scrollToProductKey }) => scrollToProductKey,
            },
        ],
        productSpecificAlert: [
            null as BillingAlertConfig | null,
            {
                setProductSpecificAlert: (_, { productSpecificAlert }) => productSpecificAlert,
            },
        ],
        showLicenseDirectInput: [
            false,
            {
                setShowLicenseDirectInput: (_, { show }) => show,
            },
        ],
        redirectPath: [
            '' as string,
            {
                setRedirectPath: (_, { redirectPath }) => redirectPath,
            },
        ],
        isOnboarding: [
            false,
            {
                setIsOnboarding: (_, { isOnboarding }) => isOnboarding,
            },
        ],
        unsubscribeError: [
            null as null | UnsubscribeError,
            {
                resetUnsubscribeError: () => null,
                setUnsubscribeError: (_, { error }) => error,
            },
        ],
        timeRemainingInSeconds: [
            0,
            {
                loadBillingSuccess: (_, { billing }) => {
                    if (!billing?.billing_period) {
                        return 0
                    }
                    const currentTime = dayjs()
                    const periodEnd = dayjs(billing.billing_period.current_period_end)
                    return periodEnd.diff(currentTime, 'second')
                },
            },
        ],
        timeTotalInSeconds: [
            0,
            {
                loadBillingSuccess: (_, { billing }) => {
                    if (!billing?.billing_period) {
                        return 0
                    }
                    const periodStart = dayjs(billing.billing_period.current_period_start)
                    const periodEnd = dayjs(billing.billing_period.current_period_end)
                    return periodEnd.diff(periodStart, 'second')
                },
            },
        ],
        isPurchaseCreditsModalOpen: [
            false,
            {
                showPurchaseCreditsModal: (_, { isOpen }) => isOpen,
            },
        ],
        isCreditCTAHeroDismissed: [
            false,
            { persist: true },
            {
                toggleCreditCTAHeroDismissed: (_, { isDismissed }) => isDismissed,
            },
        ],
        computedDiscount: [
            null as number | null,
            {
                setComputedDiscount: (_, { discount }) => discount,
            },
        ],
        creditBrackets: [
            [],
            {
                setCreditBrackets: (_, { creditBrackets }) => creditBrackets || [],
            },
        ],
        switchPlanLoading: [
            null as string | null,
            {
                setSwitchPlanLoading: (_, { productKey }) => productKey,
            },
        ],
    }),
    lazyLoaders(({ actions, values }) => ({
        billing: [
            null as BillingType | null,
            {
                loadBilling: async () => {
                    // Note: this is a temporary flag to skip forecasting in the billing page
                    // for customers running into performance issues until we have a more permanent fix
                    // of splitting the billing and forecasting data.
                    const skipForecasting = values.featureFlags[FEATURE_FLAGS.BILLING_SKIP_FORECASTING]
                    // Many scenes read billing, so a failed read keeps the last known state quietly
                    // rather than toasting on every page or reaching error tracking.
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                        const response = await api.get(
                            'api/billing' + (skipForecasting ? '?include_forecasting=false' : '')
                        )
                        return parseBillingResponse(response) ?? values.billing
                    } catch {
                        return values.billing
                    }
                },

                updateBillingLimits: async (limits: { [key: string]: number | null }) => {
                    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.
                        const response = await api.update('api/billing', { custom_limits_usd: limits })
                        lemonToast.success('Billing limits updated')
                        actions.loadBilling()
                        return parseBillingResponse(response) ?? values.billing
                    } catch (error: unknown) {
                        lemonToast.error(
                            'There was an error updating your billing limits. Please try again or contact support.'
                        )
                        // A failure, not the last billing state: a success would close the limit editor and
                        // discard the value the person was saving.
                        throw error
                    }
                },

                deactivateProduct: async (key: string, breakpoint) => {
                    // clear upgrade params from URL
                    // Note(@zach): This is not working properly. We need to look into this.
                    const currentURL = new URL(window.location.href)
                    currentURL.searchParams.delete('upgraded')
                    currentURL.searchParams.delete('products')
                    router.actions.push(currentURL.pathname + currentURL.search)

                    actions.resetUnsubscribeError()
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingDeactivateCreate() from 'products/billing/frontend/generated/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.createResponse('api/billing/deactivate', { products: key })
                        const jsonRes = await getJSONOrNull(response)

                        lemonToast.success(
                            "You have been unsubscribed. We're sad to see you go. May the hedgehogs be ever in your favor."
                        )
                        actions.reportProductUnsubscribed(key)

                        // Reload billing, user, and organization to get the updated available features
                        actions.loadBilling()
                        await breakpoint(2000) // Wait enough time for the organization to be updated
                        actions.loadUser()
                        actions.loadCurrentOrganization()

                        return parseBillingResponse(jsonRes) ?? values.billing
                    } catch (error: any) {
                        if (error.code) {
                            if (error.code === BillingAPIErrorCodes.OPEN_INVOICES_ERROR) {
                                const invoicesUrl = values.isExternallyBilled
                                    ? values.billing?.external_billing_provider_invoices_url
                                    : values.billing?.stripe_portal_url
                                actions.setUnsubscribeError({
                                    detail: error.detail,
                                    link: invoicesUrl ? (
                                        <Link to={invoicesUrl} target="_blank">
                                            View invoices
                                        </Link>
                                    ) : undefined,
                                } as UnsubscribeError)
                            } else if (error.code === BillingAPIErrorCodes.NO_ACTIVE_PAYMENT_METHOD_ERROR) {
                                actions.setUnsubscribeError({
                                    detail: error.detail,
                                } as UnsubscribeError)
                            } else if (error.code === BillingAPIErrorCodes.COULD_NOT_PAY_INVOICES_ERROR) {
                                const invoicesUrl = values.isExternallyBilled
                                    ? values.billing?.external_billing_provider_invoices_url
                                    : error.link || values.billing?.stripe_portal_url
                                actions.setUnsubscribeError({
                                    detail: error.detail,
                                    link: invoicesUrl ? (
                                        <Link to={invoicesUrl} target="_blank">
                                            {error.link && !values.isExternallyBilled
                                                ? 'View invoice'
                                                : 'View invoices'}
                                        </Link>
                                    ) : undefined,
                                } as UnsubscribeError)
                            }
                        } else {
                            actions.setUnsubscribeError({
                                detail:
                                    typeof error.detail === 'string'
                                        ? error.detail
                                        : `We encountered a problem. Please try again or submit a support ticket.`,
                            } as UnsubscribeError)
                        }
                        console.error(error)
                        // This is a bit of a hack to prevent the page from re-rendering.
                        return values.billing
                    }
                },
                switchFlatrateSubscriptionPlan: async (data: SwitchPlanPayload, breakpoint) => {
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingSubscriptionSwitchPlanCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                        await api.create('api/billing/subscription/switch-plan', data)

                        const productDisplayName = capitalizeFirstLetter(data.to_product_key)
                        lemonToast.success(`You're now on ${productDisplayName}`)
                        actions.setSwitchPlanLoading(null)

                        // Reload billing, user, and organization to get the updated available features
                        actions.loadBilling()
                        await breakpoint(2000)
                        actions.loadUser()
                        actions.loadCurrentOrganization()

                        return values.billing as BillingType
                    } catch (error: any) {
                        posthog.captureException(error)
                        lemonToast.error(
                            (error && error.detail) ||
                                'There was an error switching your plan. Please try again or contact support.'
                        )
                        actions.setSwitchPlanLoading(null)
                        // Keep the current billing state on failure
                        return values.billing as BillingType
                    }
                },
            },
        ],
        openInvoices: [
            null as OpenInvoices | null,
            {
                loadInvoices: async (): Promise<OpenInvoices | null> => {
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingGetInvoicesRetrieve() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                        const res = await api.getResponse('api/billing/get_invoices?status=open')
                        const jsonRes = await getJSONOrNull(res)
                        return { count: jsonRes['count'], link: jsonRes['link'] }
                    } catch (error: any) {
                        console.error(error)
                    }
                    return null
                },
            },
        ],
        creditOverview: [
            {
                eligible: false,
                estimated_monthly_credit_amount_usd: null,
                status: 'none',
                invoice_url: null,
                collection_method: null,
                cc_last_four: null,
                email: null,
                credit_brackets: [],
            },
            {
                loadCreditOverview: async () => {
                    // Check if the user is subscribed
                    if (values.billing?.has_active_subscription) {
                        // A failed or empty read keeps the last overview rather than breaking the page.
                        let response
                        try {
                            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingCreditsOverviewRetrieve() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                            response = await api.get('api/billing/credits/overview')
                        } catch {
                            return values.creditOverview
                        }
                        if (!response) {
                            return values.creditOverview
                        }

                        if (!values.creditForm.creditInput) {
                            const spend =
                                response.estimated_monthly_credit_amount_usd ??
                                DEFAULT_ESTIMATED_MONTHLY_CREDIT_AMOUNT_USD

                            actions.setCreditBrackets(response.credit_brackets)
                            actions.setCreditFormValue('creditInput', Math.round(spend * 12))
                        }

                        if (response.eligible && response.status === 'none') {
                            actions.reportCreditsCTAShown(response)
                        }

                        return response
                    }
                    // Return default values if not subscribed
                    return {
                        eligible: false,
                        estimated_monthly_credit_amount_usd: null,
                        status: 'none',
                        invoice_url: null,
                        collection_method: null,
                        cc_last_four: null,
                        email: null,
                        credit_brackets: [],
                    }
                },
            },
        ],
        products: [
            [] as BillingProductV2Type[],
            {
                loadProducts: async () => {
                    // 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.
                    const response = await api.get('api/billing/available_products')
                    return response
                },
            },
        ],
    })),
    selectors({
        /** The alert to show: a Superpowers fake while one is picked, the real alert otherwise. */
        effectiveBillingAlert: [
            (s) => [s.billingAlert, s.fakeBillingAlert],
            (billingAlert: BillingAlertConfig | null, fakeBillingAlert: FakeBillingAlert): BillingAlertConfig | null =>
                buildFakeBillingAlert(fakeBillingAlert) ?? billingAlert,
        ],
        minimumBillingAccessLevel: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): OrganizationMembershipLevel =>
                getMinimumBillingAccessLevel(!!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]),
        ],
        canAccessBilling: [
            (s) => [s.currentOrganization, s.featureFlags],
            (
                currentOrganization: null | import('~/types').OrganizationType,
                featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet
            ): boolean =>
                canAccessBillingUtil(
                    currentOrganization?.membership_level,
                    !!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]
                ),
        ],
        minimumUsageSpendReadAccessLevel: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): OrganizationMembershipLevel =>
                getMinimumUsageSpendReadAccessLevel(
                    isMemberUsageSpendReadAccessEnabled(featureFlags),
                    !!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]
                ),
        ],
        canViewUsageAndSpend: [
            (s) => [s.currentOrganization, s.featureFlags],
            (currentOrganization: OrganizationType | null, featureFlags: FeatureFlagsSet): boolean =>
                canViewUsageAndSpendUtil(
                    currentOrganization?.membership_level,
                    isMemberUsageSpendReadAccessEnabled(featureFlags),
                    !!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]
                ),
        ],
        canOnlyViewUsageAndSpend: [
            (s) => [s.canViewUsageAndSpend, s.canAccessBilling],
            (canViewUsageAndSpend: boolean, canAccessBilling: boolean): boolean =>
                canViewUsageAndSpend && !canAccessBilling,
        ],
        billingEntryUrl: [
            (s) => [s.canAccessBilling, s.canOnlyViewUsageAndSpend],
            (canAccessBilling: boolean, canOnlyViewUsageAndSpend: boolean): string | null => {
                if (canAccessBilling) {
                    return urls.organizationBillingSection('overview')
                }
                if (canOnlyViewUsageAndSpend) {
                    return urls.organizationBillingSection('usage')
                }
                return null
            },
        ],
        upgradeLink: [(s) => [s.preflight], (): string => '/organization/billing'],
        isUnlicensedDebug: [
            (s) => [s.preflight, s.billing],
            (preflight: null | import('~/types').PreflightStatus, billing: BillingType | null): boolean =>
                !!preflight?.is_debug && !billing?.billing_period,
        ],
        supportPlans: [
            (s) => [s.billing],
            (billing: BillingType): BillingPlanType[] => {
                const platformAndSupportProduct = billing?.products?.find(
                    (product) => product.type == ProductKey.PLATFORM_AND_SUPPORT
                )
                if (!platformAndSupportProduct?.plans) {
                    return []
                }

                const addonPlans = platformAndSupportProduct?.addons?.map((addon) => addon.plans).flat()
                const insertionIndex = Math.max(0, (platformAndSupportProduct?.plans?.length ?? 1) - 1)
                const allPlans = platformAndSupportProduct?.plans?.slice(0) || []
                allPlans.splice(insertionIndex, 0, ...addonPlans)
                return allPlans
            },
        ],
        hasSupportAddonPlan: [
            (s) => [s.billing],
            (billing: BillingType): boolean => {
                return !!billing?.products
                    ?.find((product) => product.type == ProductKey.PLATFORM_AND_SUPPORT)
                    ?.addons.find((addon) => addon.plans.find((plan) => plan.current_plan))
            },
        ],
        platformAddons: [
            (s) => [s.billing],
            (billing: BillingType): BillingProductV2AddonType[] => {
                const platformProduct = billing?.products?.find(
                    (product: BillingProductV2Type) => product.type === ProductKey.PLATFORM_AND_SUPPORT
                )
                return platformProduct?.addons ?? []
            },
        ],
        currentPlatformAddon: [
            (s) => [s.billing],
            (billing: BillingType): BillingProductV2AddonType | null => {
                const platformProduct = billing?.products?.find(
                    (product: BillingProductV2Type) => product.type === ProductKey.PLATFORM_AND_SUPPORT
                )
                return platformProduct?.addons?.find((addon: BillingProductV2AddonType) => !!addon.subscribed) || null
            },
        ],
        currentPlatformAddonPlan: [
            (s) => [s.currentPlatformAddon],
            (currentPlatformAddon: BillingProductV2AddonType | null): BillingPlanType | null =>
                currentPlatformAddon?.plans?.find((plan) => plan.current_plan) ??
                currentPlatformAddon?.plans?.[0] ??
                null,
        ],
        productAnalyticsPlans: [
            (s) => [s.billing],
            (billing: BillingType | null): BillingPlanType[] =>
                billing?.products?.find((product) => product.type === ProductKey.PRODUCT_ANALYTICS)?.plans ?? [],
        ],
        productAnalyticsFreePlan: [
            (s) => [s.productAnalyticsPlans],
            (productAnalyticsPlans: BillingPlanType[]): BillingPlanType | null =>
                productAnalyticsPlans.find((plan) => !!plan.free_allocation && !plan.tiers) ?? null,
        ],
        productAnalyticsPlanReplacingGrandfathered: [
            (s) => [s.productAnalyticsPlans],
            (productAnalyticsPlans: BillingPlanType[]): BillingPlanType | null =>
                productAnalyticsPlans.find(
                    (plan) => !!plan.tiers && plan.plan_key !== GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY
                ) ?? null,
        ],
        hasGrandfatheredEventsRetention: [
            (s) => [s.productAnalyticsPlans, s.productAnalyticsPlanReplacingGrandfathered],
            (
                productAnalyticsPlans: BillingPlanType[],
                productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
            ): boolean =>
                !!productAnalyticsPlanReplacingGrandfathered &&
                productAnalyticsPlans.some(
                    (plan) => !!plan.current_plan && plan.plan_key === GRANDFATHERED_EVENTS_RETENTION_PLAN_KEY
                ),
        ],
        productAnalyticsPlanAfterPackageDowngrade: [
            (s) => [
                s.productAnalyticsPlans,
                s.hasGrandfatheredEventsRetention,
                s.productAnalyticsPlanReplacingGrandfathered,
            ],
            (
                productAnalyticsPlans: BillingPlanType[],
                hasGrandfatheredEventsRetention: boolean,
                productAnalyticsPlanReplacingGrandfathered: BillingPlanType | null
            ): BillingPlanType | null =>
                hasGrandfatheredEventsRetention
                    ? productAnalyticsPlanReplacingGrandfathered
                    : (productAnalyticsPlans.find((plan) => !!plan.current_plan) ?? null),
        ],
        currentEventsRetentionMonths: [
            (s) => [s.currentOrganization],
            (currentOrganization: OrganizationType | null): number | null =>
                eventsRetentionMonths(currentOrganization?.available_product_features),
        ],
        unusedPlatformAddonAmount: [
            (s) => [s.currentPlatformAddon, s.timeRemainingInSeconds, s.timeTotalInSeconds],
            (
                currentPlatformAddon: BillingProductV2AddonType | null,
                timeRemainingInSeconds: number,
                timeTotalInSeconds: number
            ): number => {
                if (!currentPlatformAddon || !timeTotalInSeconds) {
                    return 0
                }
                const unitAmount = parseFloat(currentPlatformAddon.current_amount_usd || '0')
                const ratio = Math.max(0, Math.min(1, timeRemainingInSeconds / timeTotalInSeconds))
                const amount = unitAmount * ratio
                return Math.round(amount * 100) / 100
            },
        ],
        creditDiscount: [(s) => [s.computedDiscount], (computedDiscount: number | null) => computedDiscount || 0],
        billingPlan: [
            (s) => [s.billing],
            (billing: BillingType | null): BillingPlan | null => billing?.billing_plan || null,
        ],
        supportResponseTime: [
            (s) => [s.billing, s.billingPlan, s.supportPlans, s.currentOrganization],
            (
                billing: BillingType | null,
                billingPlan: BillingPlan | null,
                supportPlans: BillingPlanType[],
                currentOrganization: OrganizationType | null
            ): string | null =>
                getSupportResponseTime({
                    billing,
                    billingPlan,
                    supportPlans,
                    organizationId: currentOrganization?.id,
                }),
        ],
        startupProgramLabelCurrent: [
            (s) => [s.billing],
            (billing: BillingType | null): StartupProgramLabel | null => billing?.startup_program_label || null,
        ],
        startupProgramLabelPrevious: [
            (s) => [s.billing],
            (billing: BillingType | null): StartupProgramLabel | null =>
                billing?.startup_program_label_previous || null,
        ],
        ycCreditsState: [
            (s) => [s.billing],
            (billing: BillingType | null): YcCreditsState | null => {
                if (billing?.startup_program_label !== StartupProgramLabel.YC) {
                    return null
                }
                const hasCredits = Number(billing.discount_amount_usd ?? 0) > 0
                // Older billing responses do not send the field, so only an explicit false stops the renewal copy
                if (billing.startup_program_credits_renew === false) {
                    return hasCredits ? 'ending' : 'ended'
                }
                return hasCredits ? 'renewing' : 'used_until_renewal'
            },
        ],
        isAnnualPlanCustomer: [
            (s) => [s.billing],
            (billing: BillingType | null): boolean => billing?.is_annual_plan_customer || false,
        ],
        isProductAtOrOverUsageLimit: [
            (s) => [s.billing],
            (billing: BillingType | null): ((productKey: ProductKey) => boolean) =>
                (productKey: ProductKey): boolean => {
                    const product = billing?.products?.find((p) => p.type === productKey)
                    return isUsageAtOrOverLimit(product?.percentage_usage)
                },
        ],
        billingPeriodUTC: [
            (s) => [s.billing],
            (billing: BillingType | null): BillingPeriod => ({
                start: billing?.billing_period?.current_period_start?.utc() || null,
                end: billing?.billing_period?.current_period_end?.utc() || null,
                interval: billing?.billing_period?.interval || null,
            }),
        ],
        showBillingSummary: [
            (s) => [s.billing, s.isOnboarding],
            (billing: BillingType | null, isOnboarding: boolean): boolean => {
                return !isOnboarding && !!billing?.billing_period
            },
        ],
        isBillingManagedByPartner: [
            (s) => [s.billing],
            (billing: BillingType | null): boolean => !!billing?.billing_managed_by_partner,
        ],
        billingManagedByPartnerDisabledReason: [
            (s) => [s.billing],
            (billing: BillingType | null): string | null => {
                const partner = billing?.billing_managed_by_partner
                if (!partner) {
                    return null
                }
                return `Billing for this organization is managed by ${partner.partner_name.trim() || 'your partner'}.`
            },
        ],
        billingManagedByPartnerNotice: [
            (s) => [s.billingManagedByPartnerDisabledReason],
            (billingManagedByPartnerDisabledReason: string | null): string | null =>
                billingManagedByPartnerDisabledReason
                    ? `${billingManagedByPartnerDisabledReason} Contact them to change your plan or payment details.`
                    : null,
        ],
        isBillingManagedByVercel: [
            (s) => [s.billing],
            (billing: BillingType | null): boolean => billing?.billing_provider === BillingProvider.Vercel,
        ],
        billingManagedByVercelDisabledReason: [
            (s) => [s.billing, s.isBillingManagedByVercel],
            (billing: BillingType | null, isBillingManagedByVercel: boolean): string | null =>
                isBillingManagedByVercel && !billing?.has_active_subscription
                    ? 'Billing for this organization is managed by Vercel. Contact support to change your plan.'
                    : null,
        ],
        billingManagedByVercelNotice: [
            (s) => [s.isBillingManagedByVercel, s.billingManagedByVercelDisabledReason],
            (isBillingManagedByVercel: boolean, billingManagedByVercelDisabledReason: string | null): string | null => {
                if (!isBillingManagedByVercel) {
                    return null
                }
                return (
                    billingManagedByVercelDisabledReason ??
                    'Billing for this organization is managed by Vercel, including the payment method and invoices. To cap your spend, set a billing limit on each product on this page.'
                )
            },
        ],
        selfServeBillingDisabledReason: [
            (s) => [s.billingManagedByPartnerDisabledReason, s.billingManagedByVercelDisabledReason],
            (
                billingManagedByPartnerDisabledReason: string | null,
                billingManagedByVercelDisabledReason: string | null
            ): string | null => billingManagedByPartnerDisabledReason ?? billingManagedByVercelDisabledReason,
        ],
        selfServeBillingNotice: [
            (s) => [s.billingManagedByPartnerNotice, s.billingManagedByVercelDisabledReason],
            (
                billingManagedByPartnerNotice: string | null,
                billingManagedByVercelDisabledReason: string | null
            ): string | null => billingManagedByPartnerNotice ?? billingManagedByVercelDisabledReason,
        ],
        showCreditCTAHero: [
            (s) => [s.creditOverview, s.isBillingManagedByPartner],
            (
                creditOverview: {
                    cc_last_four: null
                    collection_method: null
                    credit_brackets: never[]
                    eligible: false
                    email: null
                    estimated_monthly_credit_amount_usd: null
                    invoice_url: null
                    status: string
                },
                isBillingManagedByPartner: boolean
            ): boolean => {
                const isEligible = creditOverview.eligible
                return !isBillingManagedByPartner && isEligible && creditOverview.status !== 'paid'
            },
        ],
        showBillingHero: [
            (s) => [s.billing, s.billingPlan, s.showCreditCTAHero, s.selfServeBillingDisabledReason],
            (
                billing: BillingType | null,
                billingPlan: BillingPlan | null,
                showCreditCTAHero: boolean,
                selfServeBillingDisabledReason: string | null
            ): boolean => {
                const platformAndSupportProduct = billing?.products?.find(
                    (product) => product.type === ProductKey.PLATFORM_AND_SUPPORT
                )
                return (
                    !!billingPlan &&
                    !!platformAndSupportProduct &&
                    !showCreditCTAHero &&
                    !selfServeBillingDisabledReason
                )
            },
        ],
        isManagedAccount: [
            (s) => [s.billing],
            (billing: BillingType): boolean => {
                return !!(billing?.account_owner?.name || billing?.account_owner?.email)
            },
        ],
        isExternallyBilled: [
            (s) => [s.billing],
            (billing: BillingType | null): boolean =>
                (!!billing?.billing_provider && billing.billing_provider !== BillingProvider.PostHog) ||
                !!billing?.external_billing_provider_invoices_url,
        ],
        billingError: [
            (s) => [s.openInvoices, s.billing, s.isExternallyBilled],
            (
                openInvoices: OpenInvoices | null,
                billing: BillingType | null,
                isExternallyBilled: boolean
            ): BillingError | null => {
                if (!billing || !openInvoices?.count) {
                    return null
                }
                const numOpenInvoices = openInvoices.count
                const stripeInvoicesUrl =
                    numOpenInvoices == 1 && openInvoices.link ? openInvoices.link : billing.stripe_portal_url
                const invoicesUrl = isExternallyBilled
                    ? billing.external_billing_provider_invoices_url
                    : stripeInvoicesUrl
                if (!invoicesUrl) {
                    return null
                }
                const viewInvoicesButton = {
                    to: invoicesUrl,
                    children: `View invoice${isExternallyBilled || numOpenInvoices > 1 ? 's' : ''}`,
                    targetBlank: true,
                }
                return {
                    status: 'warning',
                    message: `You have ${numOpenInvoices} open invoice${
                        numOpenInvoices > 1 ? 's' : ''
                    }. Please pay ${numOpenInvoices > 1 ? 'them' : 'it'} before adding items to your subscription.`,
                    action: viewInvoicesButton,
                }
            },
        ],
        accountOwner: [
            (s) => [s.billing],
            (billing: BillingType): { name?: string; email?: string } | null => billing?.account_owner || null,
        ],
        estimatedMonthlyCreditAmountUsd: [
            (s) => [s.creditOverview],
            (creditOverview: {
                cc_last_four: null
                collection_method: null
                credit_brackets: never[]
                eligible: false
                email: null
                estimated_monthly_credit_amount_usd: null
                invoice_url: null
                status: string
            }): number | null => {
                if (creditOverview === null) {
                    return null
                }

                if (
                    creditOverview.estimated_monthly_credit_amount_usd === null ||
                    creditOverview.estimated_monthly_credit_amount_usd === undefined
                ) {
                    return DEFAULT_ESTIMATED_MONTHLY_CREDIT_AMOUNT_USD
                }

                return creditOverview.estimated_monthly_credit_amount_usd
            },
        ],
    }),
    forms(({ actions, values }) => ({
        activateLicense: {
            defaults: { license: '' } as { license: string },
            errors: ({ license }) => ({
                license: !license ? 'Please enter your license key' : undefined,
            }),
            submit: async ({ license }, breakpoint) => {
                await breakpoint(500)
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingLicensePartialUpdate() from 'products/billing/frontend/generated/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/billing/license', {
                        license,
                    })

                    // Reset the URL so we don't trigger the license submission again
                    router.actions.replace(
                        `/${values.isOnboarding ? 'ingestion' : 'organization'}/billing?success=true`
                    )
                    setTimeout(() => {
                        window.location.reload() // Permissions, projects etc will be out of date at this point, so refresh
                    }, 100)
                } catch (e: any) {
                    actions.setActivateLicenseManualErrors({
                        license: e.detail || 'License could not be activated. Please contact support.',
                    })
                    throw e
                }
            },
        },
        creditForm: {
            defaults: {
                creditInput: '',
                collectionMethod: 'charge_automatically',
            },
            submit: async ({ creditInput, collectionMethod }) => {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingCreditsPurchaseCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                await api.create('api/billing/credits/purchase', {
                    annual_credit_amount_usd: +creditInput,
                    collection_method: collectionMethod,
                })

                actions.showPurchaseCreditsModal(false)
                actions.loadCreditOverview()
                actions.reportCreditsFormSubmitted(+creditInput)

                const billingUrl = values.isExternallyBilled
                    ? values.billing?.external_billing_provider_invoices_url
                    : values.billing?.stripe_portal_url
                LemonDialog.open({
                    title: 'Your credit purchase has been submitted',
                    width: 536,
                    content:
                        collectionMethod === 'send_invoice' ? (
                            <>
                                <p className="mb-4">
                                    The invoice for your credits has been created and it will be emailed to the email on
                                    file.
                                </p>
                                <p>
                                    Once the invoice is paid we will apply the credits to your account. Until the
                                    invoice is paid you will be charged for usage as normal.
                                </p>
                            </>
                        ) : values.isExternallyBilled ? (
                            <p>
                                Your billing provider will collect the payment, and the credits will be applied to your
                                account once it does.
                                {billingUrl ? (
                                    <>
                                        {' '}
                                        Please make sure your{' '}
                                        <Link to={billingUrl} target="_blank">
                                            payment method with your provider
                                        </Link>{' '}
                                        is up to date.
                                    </>
                                ) : null}
                            </p>
                        ) : (
                            <>
                                <p>
                                    Your card will be charged soon and the credits will be applied to your account.
                                    Please make sure your{' '}
                                    {billingUrl ? (
                                        <Link to={billingUrl} target="_blank">
                                            card on file
                                        </Link>
                                    ) : (
                                        'card on file'
                                    )}{' '}
                                    is up to date. You will receive an email when the credits are applied.
                                </p>
                            </>
                        ),
                })
            },
            errors: ({ creditInput, collectionMethod }) => ({
                creditInput: !creditInput
                    ? 'Please enter the amount of credits you want to purchase'
                    : // This value is used because 3333 - 10% = 3000
                      +creditInput < 3333
                      ? 'Please enter a credit amount of at least $3,333'
                      : undefined,
                collectionMethod: !collectionMethod ? 'Please select a collection method' : undefined,
            }),
        },
    })),
    listeners(({ actions, values, cache }) => ({
        reportBillingShown: () => {
            posthog.capture('billing v2 shown')
        },
        reportBillingAlertShown: ({ alertConfig }) => {
            posthog.capture('billing alert shown', {
                ...alertConfig,
            })
        },
        reportBillingAlertActionClicked: ({ alertConfig }) => {
            posthog.capture('billing alert action clicked', {
                ...alertConfig,
            })
        },
        reportCreditsModalShown: () => {
            posthog.capture('credits modal shown')
        },
        reportCreditsFormSubmitted: ({ creditInput }) => {
            posthog.capture('credits modal credit form submitted', {
                credit_amount_usd: creditInput,
            })
        },
        reportCreditsCTAShown: ({ creditOverview }) => {
            posthog.capture('credits cta shown', {
                eligible: creditOverview.eligible,
                status: creditOverview.status,
                estimated_monthly_credit_amount_usd: creditOverview.estimated_monthly_credit_amount_usd,
            })
        },
        toggleCreditCTAHeroDismissed: ({ isDismissed }) => {
            if (isDismissed) {
                posthog.capture('credits cta hero dismissed')
            }
        },
        switchFlatrateSubscriptionPlan: async (payload) => {
            actions.setSwitchPlanLoading(payload.to_product_key)
        },
        sceneRendered: () => {
            if (cache.loadCreditOverviewAfterScene) {
                cache.loadCreditOverviewAfterScene = false
                actions.loadCreditOverview()
            }
        },
        loadBillingSuccess: async ({ payload }, breakpoint) => {
            actions.registerInstrumentationProps()
            actions.determineBillingAlert()
            // Scoped payment refreshes update their organization's entitlements separately.
            // The endpoints below read the server's selected organization.
            if (payload) {
                return
            }
            // Only billing views show credits, so this request waits for the scene's own requests.
            if (values.sceneHasRendered) {
                actions.loadCreditOverview()
            } else {
                cache.loadCreditOverviewAfterScene = true
            }

            // If the activation is successful, we reload the user/organization to get the updated available features
            // activation can be triggered from the billing page or onboarding
            if (
                (router.values.location.pathname.includes('/organization/billing') ||
                    router.values.location.pathname.includes('/onboarding')) &&
                (router.values.searchParams['success'] || router.values.searchParams['upgraded'])
            ) {
                // Wait enough time for the organization to be updated
                await breakpoint(1000)
                actions.loadUser()
                actions.loadCurrentOrganization()
                // Clear the params from the billing page so we don't trigger the activation again
                if (router.values.location.pathname.includes('/organization/billing')) {
                    router.actions.replace('/organization/billing')
                }
            }
        },
        determineBillingAlert: () => {
            const clearBillingAlert = (): void => {
                if (values.billingAlert) {
                    actions.setBillingAlert(null)
                }
            }

            if (values.productSpecificAlert) {
                actions.setBillingAlert(values.productSpecificAlert)
                return
            }

            if (values.billingAlert && !isManagedBillingAlert(values.billingAlert)) {
                return
            }

            if (!values.billing || !values.preflight?.cloud) {
                clearBillingAlert()
                return
            }

            const trial = values.billing.trial
            if (trial && trial.expires_at && dayjs(trial.expires_at).isAfter(dayjs())) {
                if (trial.type === 'autosubscribe' || trial.status !== 'active') {
                    // Only show for standard ones (managed by sales)
                    clearBillingAlert()
                    return
                }

                const remainingDays = dayjs(trial.expires_at).diff(dayjs(), 'days')
                const remainingHours = dayjs(trial.expires_at).diff(dayjs(), 'hours')
                if (remainingHours > 72) {
                    clearBillingAlert()
                    return
                }

                const contactEmail = values.billing.account_owner?.email || '[email protected]'
                const contactName = values.billing.account_owner?.name || 'sales'
                const timeRemaining =
                    remainingHours < 24 ? pluralize(remainingHours, 'hour') : pluralize(remainingDays, 'day')
                const planName = capitalizeFirstLetter(trial.target)
                actions.setBillingAlert({
                    kind: 'trial',
                    status: 'info',
                    title: `Your free trial for the ${planName} plan ends in ${timeRemaining}. Your service will continue without interruption, and you'll be charged for the ${planName} plan.`,
                    message: `Questions? Reach out to ${contactName} at ${contactEmail}.`,
                })
                return
            }

            const billingPeriodEnd = values.billing.billing_period?.current_period_end?.format('YYYY-MM-DD')

            const productsAtOrOverLimit =
                values.billing.products?.filter((x: BillingProductV2Type) => {
                    // Companions have no billing limit, so their usage percentage is not a limit.
                    if (!isUsageAtOrOverLimit(x.percentage_usage) || !x.usage_key || isCompanionProduct(x)) {
                        return false
                    }
                    const hideProductFlag = `billing_hide_product_${x.type}`
                    if (values.featureFlags[hideProductFlag as FeatureFlagKey] === true) {
                        return false
                    }
                    if (isBillingAlertDismissed(values.currentOrganizationId, x.type, billingPeriodEnd)) {
                        return false
                    }
                    return true
                }) || []

            if (productsAtOrOverLimit.length > 0) {
                const { title, message } = buildUsageLimitReachedMessage(
                    productsAtOrOverLimit,
                    values.canAccessBilling,
                    values.minimumBillingAccessLevel,
                    values.selfServeBillingNotice
                )

                actions.setBillingAlert({
                    kind: 'usage_limit',
                    status: 'error',
                    title,
                    message,
                    dismissKey: 'usage-limit-exceeded',
                    productKey:
                        productsAtOrOverLimit.length === 1 ? (productsAtOrOverLimit[0].type as ProductKey) : undefined,
                    onClose: () => {
                        // Store dismissal for all affected products in localStorage
                        const billingPeriodEnd =
                            values.billing?.billing_period?.current_period_end?.format('YYYY-MM-DD')
                        for (const product of productsAtOrOverLimit) {
                            storeBillingAlertDismissal(values.currentOrganizationId, product.type, billingPeriodEnd)
                        }
                        actions.setBillingAlert(null)
                    },
                })
                return
            }

            actions.resetUsageLimitExceededKey()

            const productsApproachingLimit =
                values.billing.products?.filter((x: BillingProductV2Type) => {
                    if (
                        !isUsageApproachingLimit(x.percentage_usage, ALLOCATION_THRESHOLD_ALERT) ||
                        isCompanionProduct(x)
                    ) {
                        return false
                    }
                    const hideProductFlag = `billing_hide_product_${x.type}`
                    if (values.featureFlags[hideProductFlag as FeatureFlagKey] === true) {
                        return false
                    }
                    if (
                        isBillingAlertDismissed(values.currentOrganizationId, x.type, billingPeriodEnd, '-approaching')
                    ) {
                        return false
                    }
                    return true
                }) || []

            if (productsApproachingLimit.length > 0) {
                const { title, message } = buildUsageLimitApproachingMessage(
                    productsApproachingLimit,
                    values.canAccessBilling,
                    values.minimumBillingAccessLevel
                )

                actions.setBillingAlert({
                    kind: 'usage_limit',
                    status: 'info',
                    title,
                    message,
                    dismissKey: 'usage-limit-approaching',
                    productKey:
                        productsApproachingLimit.length === 1
                            ? (productsApproachingLimit[0].type as ProductKey)
                            : undefined,
                    onClose: () => {
                        // Store dismissal for all affected products
                        const billingPeriodEnd =
                            values.billing?.billing_period?.current_period_end?.format('YYYY-MM-DD')
                        for (const product of productsApproachingLimit) {
                            storeBillingAlertDismissal(
                                values.currentOrganizationId,
                                product.type,
                                billingPeriodEnd,
                                '-approaching'
                            )
                        }
                        actions.setBillingAlert(null)
                    },
                })
                return
            }

            actions.resetUsageLimitApproachingKey()
            clearBillingAlert()
        },
        setCreditFormValue: ({ name, value }) => {
            if (name === 'creditInput' || (name as FieldNamePath)?.[0] === 'creditInput') {
                const spend = +value

                for (const bracket of values.creditBrackets) {
                    if (
                        spend >= bracket.annual_credit_from_inclusive &&
                        spend < (bracket.annual_credit_to_exclusive || Infinity)
                    ) {
                        actions.setComputedDiscount(bracket.discount)
                        return
                    }
                }

                actions.setComputedDiscount(0)
            }
        },
        registerInstrumentationProps: async (_, breakpoint) => {
            await breakpoint(100)
            if (posthog && values.billing) {
                const payload: { [key: string]: any } = {
                    has_billing_plan: !!values.billing.has_active_subscription,
                    free_trial_until: values.billing.free_trial_until?.toISOString(),
                    current_total_amount_usd: values.billing.current_total_amount_usd,
                }
                if (values.billing.products) {
                    const customLimitsUsd = values.billing.custom_limits_usd ?? {}
                    const customLimitKeysToSync = new Set<string>([
                        ...values.registeredCustomLimitKeys,
                        ...Object.keys(customLimitsUsd),
                    ])
                    const registeredCustomLimitKeys = new Set<string>()
                    for (const product of values.billing.products) {
                        customLimitKeysToSync.add(product.type)
                        if (product.usage_key) {
                            customLimitKeysToSync.add(product.usage_key)
                        }
                    }
                    for (const product of customLimitKeysToSync) {
                        const customLimitUsd = customLimitsUsd[product]
                        const property = `custom_limits_usd.${product}`
                        if (customLimitUsd === null || customLimitUsd === undefined) {
                            if (
                                values.registeredCustomLimitKeys.includes(product) ||
                                posthog.get_property(property) !== undefined
                            ) {
                                posthog.unregister(property)
                            }
                        } else {
                            registeredCustomLimitKeys.add(product)
                            payload[property] = customLimitUsd
                        }
                    }
                    actions.setRegisteredCustomLimitKeys([...registeredCustomLimitKeys])

                    for (const product of values.billing.products) {
                        const type = product.type.toLowerCase()
                        payload[`percentage_usage.${type}`] = product.percentage_usage
                        payload[`current_amount_usd.${type}`] = product.current_amount_usd
                        payload[`unit_amount_usd.${type}`] = product.unit_amount_usd
                        payload[`usage_limit.${type}`] = product.usage_limit
                        payload[`current_usage.${type}`] = product.current_usage
                        payload[`projected_usage.${type}`] = product.projected_usage
                        payload[`free_allocation.${type}`] = product.free_allocation
                    }
                }
                if (values.billing.billing_period) {
                    payload['billing_period_start'] = values.billing.billing_period.current_period_start
                    payload['billing_period_end'] = values.billing.billing_period.current_period_end
                }
                posthog.register(payload)
            }
        },
        showPurchaseCreditsModal: ({ isOpen }) => {
            if (isOpen) {
                actions.reportCreditsModalShown()
            }
        },
        scrollToProduct: ({ productType }) => {
            let element = document.querySelector(`[data-attr="billing-product-addon-${productType}"]`)
            if (element == null) {
                element = document.querySelector(`[data-attr="billing-product-${productType}"]`)
            }
            element?.scrollIntoView({
                behavior: 'smooth',
                block: 'center',
            })
        },
    })),
    urlToAction(({ actions, values }) => {
        const handleBillingRoute = (
            _params: Record<string, string | undefined>,
            _search: Record<string, unknown>,
            hash: Record<string, unknown>
        ): void => {
            if (typeof hash.license === 'string') {
                actions.setShowLicenseDirectInput(true)
                actions.setActivateLicenseValues({ license: hash.license })
                actions.submitActivateLicense()
            }
            const product = getFirstProductFromProductsParam(_search.products)
            if (product) {
                actions.setScrollToProductKey(product)
            }
            if (typeof _search.billing_error === 'string') {
                actions.setBillingAlert({
                    status: 'error',
                    title: 'Error',
                    message: _search.billing_error,
                    contactSupport: true,
                })
            }

            const redirectPath = window.location.pathname.includes('/onboarding')
                ? window.location.pathname + window.location.search
                : ''
            if (values.redirectPath !== redirectPath) {
                actions.setRedirectPath(redirectPath)
            }
            const isOnboarding = window.location.pathname.includes('/onboarding')
            if (values.isOnboarding !== isOnboarding) {
                actions.setIsOnboarding(isOnboarding)
            }
        }

        return {
            // IMPORTANT: These need to be above the "*" so they take precedence
            '/*/billing': handleBillingRoute,
            '/*/billing/overview': handleBillingRoute,
            '*': () => {
                const redirectPath = window.location.pathname.includes('/onboarding')
                    ? window.location.pathname + window.location.search
                    : ''
                if (values.redirectPath !== redirectPath) {
                    actions.setRedirectPath(redirectPath)
                }
                const isOnboarding = window.location.pathname.includes('/onboarding')
                if (values.isOnboarding !== isOnboarding) {
                    actions.setIsOnboarding(isOnboarding)
                }
            },
        }
    }),
    events(({ actions, values }) => ({
        afterMount: () => {
            const { location, searchParams, hashParams } = router.values
            const isBillingOverviewRoute =
                location.pathname.endsWith('/billing') || location.pathname.endsWith('/billing/overview')

            if (isBillingOverviewRoute) {
                if (typeof hashParams.license === 'string') {
                    actions.setShowLicenseDirectInput(true)
                    actions.setActivateLicenseValues({ license: hashParams.license })
                    actions.submitActivateLicense()
                }
                const product = getFirstProductFromProductsParam(searchParams.products)
                if (product) {
                    actions.setScrollToProductKey(product)
                }
                if (typeof searchParams.billing_error === 'string') {
                    actions.setBillingAlert({
                        status: 'error',
                        title: 'Error',
                        message: searchParams.billing_error,
                        contactSupport: true,
                    })
                }
            }

            const redirectPath = window.location.pathname.includes('/onboarding')
                ? window.location.pathname + window.location.search
                : ''
            if (values.redirectPath !== redirectPath) {
                actions.setRedirectPath(redirectPath)
            }
            const isOnboarding = window.location.pathname.includes('/onboarding')
            if (values.isOnboarding !== isOnboarding) {
                actions.setIsOnboarding(isOnboarding)
            }
        },
    })),
])