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.

26.7 KB
Raw Blame
import type { Stripe, StripeElements } from '@stripe/stripe-js'
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'

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

import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { billingLogic, parseBillingResponse } from 'lib/logic/billing/billingLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { usersPartialUpdate } from '~/generated/core/api'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { BillingProductV2Type, BillingType, OrganizationType } from '~/types'

import {
    billingActivateAuthorizeCreate,
    billingActivateAuthorizeStatusCreate,
    billingActivateCreate,
    getBillingListUrl,
} from 'products/billing/frontend/generated/api'
import type { BillingActivationRequestApi } from 'products/billing/frontend/generated/api.schemas'
import { retrieve as retrieveOrganization } from 'products/platform_features/frontend/generated/api'

import { billingProductLogic } from './billingProductLogic'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface paymentEntryLogicValues {
    apiError: string | null
    authorizationStatus: string | null
    clientSecret: string | null
    completedPaymentOrganization: {
        id: string
        name: string
    } | null
    isLoading: boolean
    paymentEntryModalOpen: boolean
    paymentFlow: PaymentFlow | null
    paymentOrganizationId: string | null
    paymentSubmitted: boolean
    redirectPath: string | null
    stripeError: string | null
    stripeReturnUrl: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface paymentEntryLogicActions {
    beginPaymentFlow: (
        organizationId: string,
        redirectPath?: string | null
    ) => {
        flow: PaymentFlow
        redirectPath: string | null
    }
    cancelPaymentFlow: () => {
        value: true
    }
    clearErrors: () => {
        value: true
    }
    completePaymentFlow: (
        redirectPath: string | null,
        searchParams: CompletionParams
    ) => {
        redirectPath: string | null
        searchParams: CompletionParams
    }
    confirmPayment: (
        stripe: Stripe,
        elements: StripeElements
    ) => {
        elements: StripeElements
        stripe: Stripe
    }
    hidePaymentEntryModal: () => {
        value: true
    }
    initiateAuthorization: () => {
        value: true
    }
    pollAuthorizationStatus: (paymentIntentId?: string) => {
        paymentIntentId: string | undefined
    }
    setApiError: (error: string | null) => {
        error: string | null
    }
    setAuthorizationStatus: (status: string | null) => {
        status: string | null
    }
    setClientSecret: (clientSecret: string | null) => {
        clientSecret: string | null
    }
    setCompletedPaymentOrganization: (organization: { id: string; name: string }) => {
        organization: {
            id: string
            name: string
        }
    }
    setLoading: (loading: boolean) => {
        loading: boolean
    }
    setRedirectPath: (redirectPath: string | null) => {
        redirectPath: string | null
    }
    setStripeError: (error: string | null) => {
        error: string | null
    }
    settlePaymentFlow: () => {
        value: true
    }
    showPaymentEntryModal: () => {
        value: true
    }
    startPaymentEntryFlow: (
        product?: BillingProductV2Type | null,
        redirectPath?: string | null
    ) => {
        product: BillingProductV2Type | null | undefined
        redirectPath: string | null | undefined
    }
    upgradeProducts: (
        products: string,
        redirectPath: string | null
    ) => {
        products: string
        redirectPath: string | null
    }
    viewCompletedPaymentOrganization: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface paymentEntryLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        paymentOrganizationId: (paymentFlow: PaymentFlow | null) => string | null
        stripeReturnUrl: (paymentOrganizationId: string | null, redirectPath: string | null) => string | null
    }
}

export type paymentEntryLogicType = MakeLogicType<
    paymentEntryLogicValues,
    paymentEntryLogicActions,
    Record<string, any>,
    paymentEntryLogicMeta
>

const PAYMENT_ORGANIZATION_ERROR = 'This payment link is missing its organization. Return to billing and start again.'

interface PaymentFlow {
    organizationId: string
    organizationName: string | null
}

type CompletionParams = Record<string, string | boolean>

const fetchBilling = async (organizationId: string): Promise<BillingType | null> => {
    const skipForecasting = featureFlagLogic.values.featureFlags[FEATURE_FLAGS.BILLING_SKIP_FORECASTING]
    // nosemgrep: prefer-codegen-api -- The generated overview response still has generic product/period fields; retain the existing parser's BillingType contract while using the generated URL and query schema.
    const response = await api.get<BillingType>(
        getBillingListUrl({
            organization_id: organizationId,
            ...(skipForecasting ? { include_forecasting: false } : {}),
        })
    )
    return parseBillingResponse(response)
}

const navigateAfterPayment = (redirectPath: string | null, searchParams: CompletionParams): void => {
    const onCallbackPage = router.values.location.pathname === urls.billingAuthorizationStatus()
    if (!redirectPath && !onCallbackPage) {
        router.actions.push(router.values.location.pathname, { ...router.values.searchParams, ...searchParams })
        return
    }
    const url = new URL(redirectPath || urls.organizationBilling(), window.location.origin)
    router.actions.push(url.pathname, { ...Object.fromEntries(url.searchParams.entries()), ...searchParams })
}

export const paymentEntryLogic = kea<paymentEntryLogicType>([
    path(['scenes', 'billing', 'PaymentEntryLogic']),
    connect({
        logic: [billingLogic],
    }),
    actions({
        setClientSecret: (clientSecret: string | null) => ({ clientSecret }),
        setLoading: (loading: boolean) => ({ loading }),
        setStripeError: (error: string | null) => ({ error }),
        setApiError: (error: string | null) => ({ error }),
        clearErrors: true,
        beginPaymentFlow: (organizationId: string, redirectPath: string | null = null) => {
            const selected = organizationLogic.values.currentOrganization
            const flow: PaymentFlow = {
                organizationId,
                organizationName: selected?.id === organizationId ? selected.name : null,
            }
            return { flow, redirectPath }
        },
        cancelPaymentFlow: true,
        settlePaymentFlow: true,
        completePaymentFlow: (redirectPath: string | null, searchParams: CompletionParams) => ({
            redirectPath,
            searchParams,
        }),
        setCompletedPaymentOrganization: (organization: { id: string; name: string }) => ({ organization }),
        viewCompletedPaymentOrganization: true,
        initiateAuthorization: true,
        confirmPayment: (stripe: Stripe, elements: StripeElements) => ({ stripe, elements }),
        pollAuthorizationStatus: (paymentIntentId?: string) => ({ paymentIntentId }),
        setAuthorizationStatus: (status: string | null) => ({ status }),
        startPaymentEntryFlow: (product?: BillingProductV2Type | null, redirectPath?: string | null) => ({
            product,
            redirectPath,
        }),
        upgradeProducts: (products: string, redirectPath: string | null) => ({ products, redirectPath }),
        showPaymentEntryModal: true,
        hidePaymentEntryModal: true,
        setRedirectPath: (redirectPath: string | null) => ({ redirectPath }),
    }),
    reducers({
        paymentFlow: [
            null as PaymentFlow | null,
            { beginPaymentFlow: (_, { flow }) => flow, cancelPaymentFlow: () => null },
        ],
        paymentSubmitted: [
            false,
            {
                confirmPayment: () => true,
                setStripeError: () => false,
                beginPaymentFlow: () => false,
                settlePaymentFlow: () => false,
            },
        ],
        completedPaymentOrganization: [
            null as { id: string; name: string } | null,
            {
                setCompletedPaymentOrganization: (_, { organization }) => organization,
                beginPaymentFlow: () => null,
                hidePaymentEntryModal: () => null,
            },
        ],
        clientSecret: [
            null as string | null,
            {
                setClientSecret: (_, { clientSecret }) => clientSecret,
                beginPaymentFlow: () => null,
                hidePaymentEntryModal: () => null,
                settlePaymentFlow: () => null,
            },
        ],
        isLoading: [
            false,
            {
                setLoading: (_, { loading }) => loading,
                beginPaymentFlow: () => false,
                hidePaymentEntryModal: () => false,
                settlePaymentFlow: () => false,
            },
        ],
        stripeError: [
            null as string | null,
            { setStripeError: (_, { error }) => error, clearErrors: () => null, beginPaymentFlow: () => null },
        ],
        apiError: [
            null as string | null,
            { setApiError: (_, { error }) => error, clearErrors: () => null, beginPaymentFlow: () => null },
        ],
        authorizationStatus: [
            null as string | null,
            { setAuthorizationStatus: (_, { status }) => status, beginPaymentFlow: () => null },
        ],
        paymentEntryModalOpen: [false, { showPaymentEntryModal: () => true, hidePaymentEntryModal: () => false }],
        redirectPath: [
            null as string | null,
            {
                setRedirectPath: (_, { redirectPath }) => redirectPath,
                beginPaymentFlow: (_, { redirectPath }) => redirectPath,
                settlePaymentFlow: () => null,
            },
        ],
    }),
    selectors({
        paymentOrganizationId: [
            (s) => [s.paymentFlow],
            (flow: PaymentFlow | null): string | null => flow?.organizationId ?? null,
        ],
        stripeReturnUrl: [
            (s) => [s.paymentOrganizationId, s.redirectPath],
            (organizationId: string | null, redirectPath: string | null): string | null => {
                if (!organizationId) {
                    return null
                }
                const url = new URL(urls.billingAuthorizationStatus(), window.location.origin)
                url.searchParams.set('organization_id', organizationId)
                if (redirectPath) {
                    url.searchParams.set('postRedirectPath', redirectPath)
                }
                return url.toString()
            },
        ],
    }),
    listeners(({ actions, asyncActions, values, cache }) => {
        // Handlers run only while the flow that started the step is still the live one.
        const runPaymentStep = async <T>(
            request: () => Promise<T>,
            onSuccess: (result: T) => void | Promise<void>,
            onError?: (error: unknown) => void
        ): Promise<void> => {
            const flow = values.paymentFlow
            const isCurrent = (): boolean => !!flow && !cache.disposables.isDisposed && values.paymentFlow === flow
            let result: T
            try {
                result = await request()
            } catch (error) {
                if (isCurrent()) {
                    onError?.(error)
                }
                return
            }
            if (isCurrent()) {
                await onSuccess(result)
            }
        }

        const activateProducts = async (
            organizationId: string,
            body: Omit<BillingActivationRequestApi, 'organization_id'>,
            redirectPath: string | null,
            searchParams: CompletionParams,
            errorMessage: string
        ): Promise<void> => {
            await runPaymentStep(
                () => billingActivateCreate({ organization_id: organizationId, ...body }),
                async (response) => {
                    if (response.success) {
                        await asyncActions.completePaymentFlow(redirectPath, searchParams)
                        return
                    }
                    actions.setLoading(false)
                    if (response.must_setup_payment) {
                        actions.showPaymentEntryModal()
                    } else {
                        lemonToast.error(response.error || 'Failed to activate subscription')
                    }
                },
                (error) => {
                    actions.setLoading(false)
                    posthog.captureException(new Error(errorMessage, { cause: error }))
                    lemonToast.error('Failed to activate subscription. Please try again.')
                }
            )
        }

        // Replacing a submitted flow would drop its result, so a new flow waits until it settles.
        const startFlow = (redirectPath: string | null): string | null => {
            if (values.paymentSubmitted) {
                lemonToast.info("We're still confirming your last payment.")
                return null
            }
            const organizationId = organizationLogic.values.currentOrganization?.id
            if (!organizationId) {
                lemonToast.error('Reload the page before updating payment details.')
                return null
            }
            actions.beginPaymentFlow(organizationId, redirectPath)
            return organizationId
        }

        return {
            beginPaymentFlow: () => {
                cache.disposables.dispose('authorizationPoll')
            },
            completePaymentFlow: async ({ redirectPath, searchParams }) => {
                const flow = values.paymentFlow
                if (!flow || cache.completedPaymentFlow === flow) {
                    return
                }
                cache.completedPaymentFlow = flow
                const { organizationId } = flow
                await runPaymentStep(
                    async (): Promise<[BillingType | null, OrganizationType | null]> => {
                        // The billing read saves the organization's new features, so read the organization after it.
                        const billing = await fetchBilling(organizationId).catch(() => null)
                        // Generated organization teams/features are readonly arrays; the stores use OrganizationType.
                        const fetchedOrganization = await retrieveOrganization(organizationId)
                            .then((organization) => organization as unknown as OrganizationType)
                            .catch(() => null)
                        return [billing, fetchedOrganization]
                    },
                    ([billing, fetchedOrganization]) => {
                        actions.settlePaymentFlow()
                        const organization = fetchedOrganization?.id === organizationId ? fetchedOrganization : null
                        if (organizationLogic.values.currentOrganization?.id !== organizationId) {
                            actions.setCompletedPaymentOrganization({
                                id: organizationId,
                                name: flow.organizationName || organization?.name || 'the original organization',
                            })
                            actions.clearErrors()
                            if (router.values.location.pathname !== urls.billingAuthorizationStatus()) {
                                actions.showPaymentEntryModal()
                            }
                            return
                        }
                        if (billing) {
                            billingLogic.actions.loadBillingSuccess(billing, organizationId)
                        }
                        if (organization) {
                            organizationLogic.actions.loadCurrentOrganizationSuccess(organization)
                            const user = userLogic.values.user
                            if (user) {
                                userLogic.actions.loadUserSuccess({ ...user, organization })
                            }
                        }
                        navigateAfterPayment(redirectPath, searchParams)
                        actions.hidePaymentEntryModal()
                    }
                )
            },
            viewCompletedPaymentOrganization: async () => {
                const organization = values.completedPaymentOrganization
                if (!organization) {
                    return
                }
                // Not userLogic.updateCurrentOrganization: it skips the switch while the cached user names this
                // organization, and that cache can lag a switch made in another tab.
                try {
                    await usersPartialUpdate('@me', { set_current_organization: organization.id })
                } catch {
                    lemonToast.error('Could not switch organization. Try again.')
                    return
                }
                sidePanelStateLogic.findMounted()?.actions.closeSidePanel()
                window.location.href = urls.organizationBilling()
            },
            startPaymentEntryFlow: async ({ product, redirectPath }) => {
                const { billing, selfServeBillingNotice } = billingLogic.values
                if (selfServeBillingNotice) {
                    lemonToast.info(selfServeBillingNotice)
                    return
                }
                const organizationId = startFlow(redirectPath || null)
                if (!organizationId) {
                    return
                }
                if (!billing?.customer_id) {
                    actions.showPaymentEntryModal()
                    return
                }
                actions.setLoading(true)
                if (product) {
                    billingProductLogic({ product }).actions.setBillingProductLoading(product.type)
                }
                try {
                    await activateProducts(
                        organizationId,
                        { products: 'all_products:', ...(product?.type ? { intent_product: product.type } : {}) },
                        redirectPath || null,
                        { upgraded: 'true' },
                        'payment entry api error - activate subscription error'
                    )
                } finally {
                    if (product) {
                        billingProductLogic({ product }).actions.setBillingProductLoading(null)
                    }
                }
            },
            upgradeProducts: async ({ products, redirectPath }) => {
                const organizationId = startFlow(redirectPath)
                if (!organizationId) {
                    return
                }
                await activateProducts(
                    organizationId,
                    { products },
                    redirectPath,
                    { upgraded: 'true', products },
                    'payment entry api error - product upgrade error'
                )
            },
            initiateAuthorization: async () => {
                if (values.completedPaymentOrganization) {
                    return
                }
                const organizationId = values.paymentOrganizationId
                if (!organizationId) {
                    actions.setApiError(PAYMENT_ORGANIZATION_ERROR)
                    return
                }
                // Two overlapping requests make billing create two Stripe customers, and the second one fails.
                if (cache.authorizationInFlight) {
                    return
                }
                const flow = values.paymentFlow
                const disposables = cache.disposables
                cache.authorizationInFlight = true
                actions.setClientSecret(null)
                actions.setLoading(true)
                actions.clearErrors()
                try {
                    await runPaymentStep(
                        () => billingActivateAuthorizeCreate({ organization_id: organizationId }),
                        (response) => {
                            actions.setClientSecret(response.clientSecret || null)
                            actions.setLoading(false)
                        },
                        (error) => {
                            posthog.captureException(
                                new Error('payment entry api error - initiate authorization error', { cause: error })
                            )
                            actions.setApiError('Failed to initialize payment')
                            actions.setLoading(false)
                        }
                    )
                } finally {
                    cache.authorizationInFlight = false
                    if (
                        !disposables.isDisposed &&
                        values.paymentEntryModalOpen &&
                        values.paymentFlow &&
                        values.paymentFlow !== flow
                    ) {
                        await asyncActions.initiateAuthorization()
                    }
                }
            },
            confirmPayment: async ({ stripe, elements }) => {
                const returnUrl = values.stripeReturnUrl
                if (!returnUrl) {
                    actions.setStripeError('Return to billing and start the payment flow again.')
                    return
                }
                actions.setLoading(true)
                const failConfirmation = (error: unknown, message: string): void => {
                    actions.setLoading(false)
                    actions.setStripeError(message)
                    posthog.captureException(new Error('payment entry stripe error', { cause: error }))
                }
                await runPaymentStep(
                    () =>
                        stripe.confirmPayment({
                            elements,
                            confirmParams: { return_url: returnUrl },
                            redirect: 'if_required',
                        }),
                    (result) => {
                        if (result.error) {
                            failConfirmation(result.error, result.error.message || 'Payment failed. Please try again.')
                        } else {
                            actions.pollAuthorizationStatus(result.paymentIntent.id)
                        }
                    },
                    (error) => failConfirmation(error, 'Payment failed. Please try again.')
                )
            },
            pollAuthorizationStatus: async ({ paymentIntentId }) => {
                const organizationId = values.paymentOrganizationId
                const redirectPath = values.redirectPath
                const intentId = paymentIntentId || new URLSearchParams(window.location.search).get('payment_intent')
                if (!organizationId) {
                    actions.setApiError(PAYMENT_ORGANIZATION_ERROR)
                    return
                }
                actions.setLoading(true)
                let attempts = 0
                const poll = async (): Promise<void> => {
                    // Only a pending retry stays registered, so a tab becoming visible cannot restart a finished poll.
                    cache.disposables.dispose('authorizationPoll')
                    await runPaymentStep(
                        () =>
                            billingActivateAuthorizeStatusCreate({
                                organization_id: organizationId,
                                payment_intent_id: intentId,
                            }),
                        async (response) => {
                            const status = response.status || (response.success ? 'success' : 'failed')
                            const errorMessage = response.error || 'Payment failed. Please try again.'
                            actions.setAuthorizationStatus(status)
                            if (status === 'success') {
                                await asyncActions.completePaymentFlow(redirectPath, { success: true })
                            } else if (status === 'failed') {
                                actions.setApiError(errorMessage)
                                posthog.captureException(
                                    new Error('payment entry api error - authorization status failed', {
                                        cause: new Error(errorMessage),
                                    })
                                )
                                actions.settlePaymentFlow()
                            } else if (++attempts < 30) {
                                cache.disposables.add(() => {
                                    const timer = setTimeout(() => void poll(), 2000)
                                    return () => clearTimeout(timer)
                                }, 'authorizationPoll')
                            } else {
                                actions.setApiError('Payment status check timed out')
                                posthog.captureException(
                                    new Error('payment entry api error - authorization status timed out', {
                                        cause: new Error(errorMessage),
                                    })
                                )
                                actions.settlePaymentFlow()
                            }
                        },
                        (error) => {
                            actions.setApiError('Failed to complete. Please refresh the page and try again.')
                            posthog.captureException(new Error('payment entry api error', { cause: error }))
                            actions.settlePaymentFlow()
                        }
                    )
                }
                await poll()
            },
            hidePaymentEntryModal: () => {
                if (!values.paymentSubmitted) {
                    actions.cancelPaymentFlow()
                }
                actions.clearErrors()
            },
        }
    }),
    afterMount(({ actions }) => {
        const params = new URLSearchParams(window.location.search)
        const organizationId = params.get('organization_id')
        if (organizationId && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(organizationId)) {
            actions.beginPaymentFlow(organizationId, params.get('postRedirectPath'))
        }
    }),
])