:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import { IconCheckCircle, IconPlus } from '@posthog/icons'
import { LemonButton, LemonButtonProps, LemonTag } from '@posthog/lemon-ui'
import { TRIAL_CANCELLATION_SURVEY_ID, UNSUBSCRIBE_SURVEY_ID } from 'lib/constants'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { BillingProductV2AddonType } from '~/types'
import { formatFlatRate } from './BillingProductAddon'
import { billingProductLogic } from './billingProductLogic'
import { ConfirmDowngradeModal } from './ConfirmDowngradeModal'
import { ConfirmPurchaseModal } from './ConfirmPurchaseModal'
import { ConfirmUpgradeModal } from './ConfirmUpgradeModal'
import { DATA_PIPELINES_CUTOFF_DATE } from './constants'
import { TrialCancellationSurveyModal } from './TrialCancellationSurveyModal'
import { UnsubscribeSurveyModal } from './UnsubscribeSurveyModal'
function reportBillingAddonPlanSwitchStarted(
fromProduct: string,
toProduct: string,
reason: 'upgrade' | 'downgrade'
): void {
const eventName =
reason === 'upgrade'
? 'billing addon subscription upgrade clicked'
: 'billing addon subscription downgrade clicked'
posthog.capture(eventName, {
from_product: fromProduct,
to_product: toProduct,
})
}
interface BillingProductAddonActionsProps {
addon: BillingProductV2AddonType
productRef?: React.RefObject<HTMLDivElement>
buttonSize?: LemonButtonProps['size']
ctaTextOverride?: string
align?: 'left' | 'right'
/** Collapse pricing into the CTA: hide the paragraph below and swap the next-to-button flat rate for the prorated amount when it applies. */
hidePricingNote?: boolean
/** Disable the purchase/trial CTA (e.g. while a sibling package is being activated). */
purchaseDisabledReason?: string
/** Called when the purchase/trial CTA is clicked, before the activation fires. */
onPurchaseClick?: () => void
}
export const BillingProductAddonActions = ({
addon,
productRef,
buttonSize,
ctaTextOverride,
align = 'right',
hidePricingNote = false,
purchaseDisabledReason,
onPurchaseClick,
}: BillingProductAddonActionsProps): JSX.Element => {
const { billing, billingError, currentPlatformAddon, switchPlanLoading, selfServeBillingDisabledReason } =
useValues(billingLogic)
const { preflight } = useValues(preflightLogic)
const {
currentAndUpgradePlans,
billingProductLoading,
trialLoading,
isSubscribedToAnotherAddon,
isDataPipelinesDeprecated,
isLowerTierThanCurrentAddon,
amountDueToday,
appliedCreditBalance,
isProrated,
surveyID,
} = useValues(billingProductLogic({ product: addon, productRef }))
const { toggleIsPricingModalOpen, reportSurveyShown, setSurveyResponse, initiateProductUpgrade, activateTrial } =
useActions(billingProductLogic({ product: addon }))
const { showConfirmUpgradeModal, showConfirmDowngradeModal, showConfirmPurchaseModal } = useActions(
billingProductLogic({ product: addon })
)
const upgradePlan = currentAndUpgradePlans?.upgradePlan
const isTrialEligible = !!addon.trial
// amountDueToday is what will actually hit the card right now — prorated and net of any credit
// balance (the same number the confirmation modal itemizes). The qualifier says which of the
// two mechanisms produced it, so "$0.00 today" is never left unexplained.
const todayPriceQualifier =
appliedCreditBalance > 0
? amountDueToday === 0
? 'covered by credits'
: 'prorated, credits applied'
: 'prorated'
const renderSubscribedActions = (): JSX.Element | null => {
if (addon.contact_support) {
return null
}
return (
<More
overlay={
<LemonButton
fullWidth
disabledReason={
(switchPlanLoading ? 'Switching plans...' : undefined) ||
(isDataPipelinesDeprecated
? `Data pipelines have moved to new, usage-based pricing with generous free allowance, and old ingestion-based pricing ended on ${DATA_PIPELINES_CUTOFF_DATE}.`
: undefined)
}
onClick={() => {
setSurveyResponse('$survey_response_1', addon.type)
reportSurveyShown(UNSUBSCRIBE_SURVEY_ID, addon.type)
}}
>
Remove add-on
</LemonButton>
}
/>
)
}
const renderTrialActions = (): JSX.Element | null => {
// Hide Cancel button only for Enterprise 'standard' trials (typically sales-managed)
if (addon.type === 'enterprise' && billing?.trial?.type !== 'autosubscribe') {
return null
}
return (
<LemonButton
type="primary"
size="small"
onClick={() => {
setSurveyResponse('$survey_response_1', addon.type)
reportSurveyShown(TRIAL_CANCELLATION_SURVEY_ID, addon.type)
}}
loading={trialLoading}
>
Cancel trial
</LemonButton>
)
}
const renderPurchaseActions = (): JSX.Element => {
const hasFlatRate = !!currentAndUpgradePlans?.upgradePlan?.flat_rate
// Drop the flat-rate label when the caller already shows the headline price, unless proration or trial applies.
const showLabel = hasFlatRate && !(hidePricingNote && !isTrialEligible && !isProrated)
return (
<>
{hasFlatRate ? (
showLabel ? (
<h4 className="leading-5 font-bold mb-0 flex gap-x-0.5 whitespace-nowrap">
{isTrialEligible ? (
<span>{addon.trial?.length} day free trial</span>
) : hidePricingNote && isProrated ? (
<span>
${amountDueToday.toFixed(2)} today ({todayPriceQualifier})
</span>
) : (
<span>{formatFlatRate(Number(upgradePlan?.unit_amount_usd), upgradePlan?.unit)}</span>
)}
</h4>
) : null
) : (
<LemonButton type="secondary" onClick={toggleIsPricingModalOpen}>
View pricing
</LemonButton>
)}
{!addon.inclusion_only && !isDataPipelinesDeprecated && (
<LemonButton
type="primary"
icon={<IconPlus />}
size={buttonSize || 'small'}
disableClientSideRouting
disabledReason={
selfServeBillingDisabledReason ||
(billingError && billingError.message) ||
(billing?.subscription_level === 'free' && 'Upgrade to add add-ons') ||
purchaseDisabledReason
}
loading={billingProductLoading === addon.type || trialLoading}
onClick={() => {
if (isTrialEligible) {
onPurchaseClick?.()
activateTrial()
} else if (hasFlatRate) {
// Flat-rate add-ons are charged immediately when a card is on file, so
// confirm the amount first. Defer onPurchaseClick (the parent "activating"
// lock) until the user actually confirms — firing it on open would strand
// the cards on "Please wait…" if they cancel, since that lock only clears
// on a billing reload.
showConfirmPurchaseModal()
} else {
onPurchaseClick?.()
initiateProductUpgrade(addon, currentAndUpgradePlans?.upgradePlan, '')
}
}}
>
{ctaTextOverride ?? (isTrialEligible ? 'Start trial' : 'Add')}
</LemonButton>
)}
</>
)
}
const renderPricingInfo = (): JSX.Element | null => {
if (
addon.inclusion_only ||
addon.contact_support ||
billing?.trial ||
addon.subscribed ||
addon.included_with_main_product ||
hidePricingNote
) {
return null
}
const pricingInfoClassName = clsx('mt-2 text-xs text-secondary', align === 'left' ? 'text-left' : 'text-right')
if (isTrialEligible && !isSubscribedToAnotherAddon) {
return (
<p className={pricingInfoClassName}>
You'll have {addon.trial?.length} days to try it out. Then you'll be charged{' '}
{formatFlatRate(Number(upgradePlan?.unit_amount_usd), upgradePlan?.unit)}.
</p>
)
}
// Fresh add or upgrade from another add-on (amountDueToday nets out unused time on the
// current add-on when switching). Downgrades don't show a pay-today line.
if (isProrated && (!isSubscribedToAnotherAddon || !isLowerTierThanCurrentAddon)) {
return (
<p className={pricingInfoClassName}>
Pay ~${amountDueToday.toFixed(2)} today ({todayPriceQualifier}) and
<br />
{formatFlatRate(Number(upgradePlan?.unit_amount_usd), upgradePlan?.unit)} every month thereafter.
</p>
)
}
return null
}
const renderDowngradeActions = (): JSX.Element | null => {
if (!upgradePlan || !currentPlatformAddon) {
return null
}
return (
<More
overlay={
<LemonButton
fullWidth
disabledReason={
selfServeBillingDisabledReason || (switchPlanLoading ? 'Switching plans...' : undefined)
}
onClick={() => {
reportBillingAddonPlanSwitchStarted(currentPlatformAddon.type, addon.type, 'downgrade')
showConfirmDowngradeModal()
}}
>
Downgrade
</LemonButton>
}
/>
)
}
const renderUpgradeActions = (): JSX.Element | null => {
if (!upgradePlan || !currentPlatformAddon) {
return null
}
const hasFlatRate = !!upgradePlan.flat_rate
const showLabel = hasFlatRate && !(hidePricingNote && !isProrated)
return (
<>
{showLabel && (
<h4 className="leading-5 font-bold mb-0 flex gap-x-0.5 whitespace-nowrap">
{hidePricingNote && isProrated ? (
<span>
${amountDueToday.toFixed(2)} today ({todayPriceQualifier})
</span>
) : (
formatFlatRate(Number(upgradePlan.unit_amount_usd), upgradePlan.unit)
)}
</h4>
)}
<LemonButton
type="primary"
disabledReason={
selfServeBillingDisabledReason || (switchPlanLoading ? 'Switching plans...' : undefined)
}
onClick={() => {
reportBillingAddonPlanSwitchStarted(currentPlatformAddon.type, addon.type, 'upgrade')
showConfirmUpgradeModal()
}}
>
Upgrade
</LemonButton>
</>
)
}
let content
if (addon.subscribed && !addon.inclusion_only) {
content = renderSubscribedActions()
} else if (addon.included_with_main_product) {
content = (
<LemonTag type="completion" icon={<IconCheckCircle />}>
Included with plan
</LemonTag>
)
} else if (billing?.trial && billing?.trial?.target === addon.type) {
// Current trial on this addon
content = renderTrialActions()
} else if (addon.type === 'enterprise') {
// Enterprise is sales-led — always route to sales (matches prod). In local dev, also offer an
// explicit override so engineers can still start the self-serve trial; it's gated on is_debug so
// it never renders in production.
content = (
<>
<LemonButton type="primary" to="https://posthog.com/talk-to-a-human" targetBlank>
Contact us
</LemonButton>
{preflight?.is_debug && (
<LemonButton
type="secondary"
size="xsmall"
loading={trialLoading || billingProductLoading === addon.type}
disabledReason={selfServeBillingDisabledReason || purchaseDisabledReason}
tooltip="Local dev only — starts the self-serve trial. Never shown in production."
onClick={() => {
onPurchaseClick?.()
if (isTrialEligible) {
activateTrial()
} else {
initiateProductUpgrade(addon, currentAndUpgradePlans?.upgradePlan, '')
}
}}
>
Local dev override
</LemonButton>
)}
</>
)
} else if (addon.contact_support) {
content = (
<LemonButton type="secondary" to="https://posthog.com/talk-to-a-human">
Contact support
</LemonButton>
)
} else if (!billing?.trial && !isSubscribedToAnotherAddon) {
// Customer is not subscribed to any trial
// We don't allow multiple add-ons to be subscribed to at the same time so this checks if the customer is subscribed to another add-on
// TODO: add support for when a customer has a Paid Plan trial
content = renderPurchaseActions()
} else if (!billing?.trial && isSubscribedToAnotherAddon && isLowerTierThanCurrentAddon) {
content = renderDowngradeActions()
} else if (!billing?.trial && isSubscribedToAnotherAddon && !isLowerTierThanCurrentAddon) {
content = renderUpgradeActions()
}
return (
<div className={clsx(align === 'right' && 'min-w-64')}>
<div
className={clsx(
'mt-2 self-center flex flex-wrap items-center gap-x-3 gap-y-1 justify-end',
align === 'left' ? 'flex-row-reverse' : 'ml-4'
)}
>
{content}
</div>
{renderPricingInfo()}
{surveyID === UNSUBSCRIBE_SURVEY_ID && <UnsubscribeSurveyModal product={addon} />}
{surveyID === TRIAL_CANCELLATION_SURVEY_ID && <TrialCancellationSurveyModal product={addon} />}
<ConfirmUpgradeModal product={addon} />
<ConfirmDowngradeModal product={addon} />
<ConfirmPurchaseModal product={addon} onConfirm={onPurchaseClick} />
</div>
)
}