: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
feat(billing): confirm before charging for a flat-rate add-on (#69884)
Roy Cohenbddcba97fc84
diff --git a/frontend/src/scenes/billing/BillingProductAddonActions.tsx b/frontend/src/scenes/billing/BillingProductAddonActions.tsxindex d8c6e2dd12e4..b35954d5679f 100644--- a/frontend/src/scenes/billing/BillingProductAddonActions.tsx+++ b/frontend/src/scenes/billing/BillingProductAddonActions.tsx@@ -15,6 +15,7 @@ import { billingLogic } from './billingLogic'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'@@ -44,8 +45,7 @@ export const BillingProductAddonActions = ({purchaseDisabledReason,onPurchaseClick,}: BillingProductAddonActionsProps): JSX.Element => {- const { billing, billingError, currentPlatformAddon, unusedPlatformAddonAmount, switchPlanLoading } =- useValues(billingLogic)+ const { billing, billingError, currentPlatformAddon, switchPlanLoading } = useValues(billingLogic)const { preflight } = useValues(preflightLogic)const {currentAndUpgradePlans,@@ -54,17 +54,29 @@ export const BillingProductAddonActions = ({isSubscribedToAnotherAddon,isDataPipelinesDeprecated,isLowerTierThanCurrentAddon,- proratedAmount,+ amountDueToday,+ appliedCreditBalance,isProrated,surveyID,} = useValues(billingProductLogic({ product: addon, productRef }))const { toggleIsPricingModalOpen, reportSurveyShown, setSurveyResponse, initiateProductUpgrade, activateTrial } =useActions(billingProductLogic({ product: addon }))- const { showConfirmUpgradeModal, showConfirmDowngradeModal } = useActions(billingProductLogic({ product: addon }))+ const { showConfirmUpgradeModal, showConfirmDowngradeModal, showConfirmPurchaseModal } = useActions(+ billingProductLogic({ product: addon })+ )const { reportBillingAddonPlanSwitchStarted } = useActions(eventUsageLogic)const upgradePlan = currentAndUpgradePlans?.upgradePlanconst 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@@ -125,7 +137,9 @@ export const BillingProductAddonActions = ({{isTrialEligible ? (<span>{addon.trial?.length} day free trial</span>) : hidePricingNote && isProrated ? (- <span>${proratedAmount.toFixed(2)} today (prorated)</span>+ <span>+ ${amountDueToday.toFixed(2)} today ({todayPriceQualifier})+ </span>) : (<span>{formatFlatRate(Number(upgradePlan?.unit_amount_usd), upgradePlan?.unit)}</span>)}@@ -150,10 +164,18 @@ export const BillingProductAddonActions = ({}loading={billingProductLoading === addon.type || trialLoading}onClick={() => {- onPurchaseClick?.()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, '')}}}@@ -188,22 +210,12 @@ export const BillingProductAddonActions = ({)}- if (isProrated && !isSubscribedToAnotherAddon) {- return (- <p className={pricingInfoClassName}>- Pay ~${proratedAmount.toFixed(2)} today (prorated) and- <br />- {formatFlatRate(Number(upgradePlan?.unit_amount_usd), upgradePlan?.unit)} every month thereafter.- </p>- )- }-- // Upgrading from another add-on to this one- if (isSubscribedToAnotherAddon && !isLowerTierThanCurrentAddon && isProrated) {- const amountDue = Math.max(0, proratedAmount - unusedPlatformAddonAmount)+ // 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 ~${amountDue.toFixed(2)} today (prorated) and+ Pay ~${amountDueToday.toFixed(2)} today ({todayPriceQualifier}) and<br />{formatFlatRate(Number(upgradePlan?.unit_amount_usd), upgradePlan?.unit)} every month thereafter.</p>@@ -242,7 +254,6 @@ export const BillingProductAddonActions = ({}const hasFlatRate = !!upgradePlan.flat_rate- const amountDue = Math.max(0, proratedAmount - unusedPlatformAddonAmount)const showLabel = hasFlatRate && !(hidePricingNote && !isProrated)return (@@ -250,7 +261,9 @@ export const BillingProductAddonActions = ({{showLabel && (<h4 className="leading-5 font-bold mb-0 flex gap-x-0.5 whitespace-nowrap">{hidePricingNote && isProrated ? (- <span>${amountDue.toFixed(2)} today (prorated)</span>+ <span>+ ${amountDueToday.toFixed(2)} today ({todayPriceQualifier})+ </span>) : (formatFlatRate(Number(upgradePlan.unit_amount_usd), upgradePlan.unit))}@@ -345,6 +358,7 @@ export const BillingProductAddonActions = ({{surveyID === TRIAL_CANCELLATION_SURVEY_ID && <TrialCancellationSurveyModal product={addon} />}<ConfirmUpgradeModal product={addon} /><ConfirmDowngradeModal product={addon} />+ <ConfirmPurchaseModal product={addon} onConfirm={onPurchaseClick} /></div>)}diff --git a/frontend/src/scenes/billing/ConfirmAddonChargeModal.tsx b/frontend/src/scenes/billing/ConfirmAddonChargeModal.tsxnew file mode 100644index 000000000000..d9a8a1759644--- /dev/null+++ b/frontend/src/scenes/billing/ConfirmAddonChargeModal.tsx@@ -0,0 +1,89 @@+import { LemonButton, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'++import { BillingInvoiceItemRow, BillingPlanType } from '~/types'++/**+ * Presentational confirmation dialog shared by ConfirmUpgradeModal (switching one platform add-on+ * for another) and ConfirmPurchaseModal (adding an add-on from scratch). It owns the modal shell,+ * the invoice-preview table, and the charge copy; each caller passes in the line-item rows and the+ * confirm/cancel actions that differ between the two flows.+ */+export interface ConfirmAddonChargeModalProps {+ isOpen: boolean+ /** Plan being subscribed to — drives the title and the recurring-charge copy. */+ targetPlan: BillingPlanType+ /** Add-on product name, e.g. "Scale". */+ productName: string+ isLoading: boolean+ /** Invoice line items to preview; the caller decides which rows the flow needs. */+ rows: BillingInvoiceItemRow[]+ /** Amount charged today, used in the summary sentence. */+ amountDue: number+ /** End of the current billing period, e.g. "Jul 31" — omitted if the period isn't loaded. */+ periodEndLabel?: string+ onCancel: () => void+ onConfirm: () => void+}++const columns: LemonTableColumns<BillingInvoiceItemRow> = [+ {+ title: 'Description',+ dataIndex: 'description',+ render: (_, row) => (+ <div className={`py-1 ${row.isBold ? 'font-bold' : 'font-medium'}`}>+ <div>{row.description}</div>+ {row.dateRange && <div className="text-muted text-xs">{row.dateRange}</div>}+ </div>+ ),+ },+ {+ title: 'Amount',+ dataIndex: 'amount',+ align: 'right',+ render: (_, row) => <div className={`py-1 ${row.isBold ? 'font-bold' : ''}`}>{row.amount}</div>,+ },+]++export function ConfirmAddonChargeModal({+ isOpen,+ targetPlan,+ productName,+ isLoading,+ rows,+ amountDue,+ periodEndLabel,+ onCancel,+ onConfirm,+}: ConfirmAddonChargeModalProps): JSX.Element {+ return (+ <LemonModal+ onClose={onCancel}+ isOpen={isOpen}+ closable={false}+ title={`Ready to subscribe to ${targetPlan.name}?`}+ footer={+ <>+ <LemonButton+ type="secondary"+ onClick={onCancel}+ disabledReason={isLoading ? 'Subscription update in progress, do not close this modal' : ''}+ >+ Cancel+ </LemonButton>+ <LemonButton type="primary" onClick={onConfirm} loading={isLoading}>+ Confirm+ </LemonButton>+ </>+ }+ >+ <div className="max-w-140">+ <p>+ You'll get access to all {productName} features right away. ${amountDue.toFixed(2)} will be charged+ now{periodEndLabel ? ` for the remaining period until ${periodEndLabel}` : ''}, and $+ {targetPlan.unit_amount_usd} every {targetPlan.unit} thereafter.+ </p>+ <LemonTable dataSource={rows} columns={columns} className="mt-4" uppercaseHeader={false} />+ </div>+ </LemonModal>+ )+}diff --git a/frontend/src/scenes/billing/ConfirmPurchaseModal.tsx b/frontend/src/scenes/billing/ConfirmPurchaseModal.tsxnew file mode 100644index 000000000000..30a99ee80fb5--- /dev/null+++ b/frontend/src/scenes/billing/ConfirmPurchaseModal.tsx@@ -0,0 +1,85 @@+import { useActions, useValues } from 'kea'++import { dayjs } from 'lib/dayjs'+import { billingLogic } from 'scenes/billing/billingLogic'+import { billingProductLogic } from 'scenes/billing/billingProductLogic'++import { BillingInvoiceItemRow, BillingProductV2AddonType } from '~/types'++import { ConfirmAddonChargeModal } from './ConfirmAddonChargeModal'++/**+ * Confirmation shown before charging for a fresh flat-rate add-on purchase (e.g. adding Scale).+ * Sibling of ConfirmUpgradeModal, which covers switching one platform add-on for another; this+ * covers adding an add-on when there is nothing to switch from. Without it, clicking "Add" with a+ * card on file charged immediately with no summary of what was about to be billed.+ */+export function ConfirmPurchaseModal({+ product,+ onConfirm,+}: {+ product: BillingProductV2AddonType+ // Fired when the user confirms (not when the modal opens), so the caller can start any+ // parent "activating" lock only once a charge is actually happening.+ onConfirm?: () => void+}): JSX.Element | null {+ const { billing } = useValues(billingLogic)+ const {+ currentAndUpgradePlans,+ confirmPurchaseModalOpen,+ proratedAmount,+ appliedCreditBalance,+ amountDueToday,+ billingProductLoading,+ } = useValues(billingProductLogic({ product }))+ const { hideConfirmPurchaseModal, confirmProductPurchase } = useActions(billingProductLogic({ product }))++ const targetPlan = currentAndUpgradePlans?.upgradePlan+ const periodEnd = billing?.billing_period?.current_period_end++ // Require a loaded billing period: without it proratedAmount falls back to 0, which would+ // misleadingly show "$0.00 due today" for a charge the backend still applies at the full rate.+ if (!confirmPurchaseModalOpen || !targetPlan || !periodEnd) {+ return null+ }++ const remainingPeriodFormatted = `${dayjs().format('MMM D')} - ${periodEnd.format('MMM D, YYYY')}`++ const rows: BillingInvoiceItemRow[] = [+ {+ description: `Remaining time on ${product.name}`,+ dateRange: remainingPeriodFormatted,+ amount: `$${proratedAmount.toFixed(2)}`,+ },+ ]++ if (appliedCreditBalance > 0) {+ rows.push({+ description: 'Applied balance',+ amount: `-$${appliedCreditBalance.toFixed(2)}`,+ })+ }++ rows.push({+ description: 'Amount due today',+ amount: `$${amountDueToday.toFixed(2)}`,+ isBold: true,+ })++ return (+ <ConfirmAddonChargeModal+ isOpen={confirmPurchaseModalOpen}+ targetPlan={targetPlan}+ productName={product.name}+ isLoading={billingProductLoading === product.type}+ rows={rows}+ amountDue={amountDueToday}+ periodEndLabel={periodEnd.format('MMM D')}+ onCancel={hideConfirmPurchaseModal}+ onConfirm={() => {+ onConfirm?.()+ confirmProductPurchase()+ }}+ />+ )+}diff --git a/frontend/src/scenes/billing/ConfirmUpgradeModal.tsx b/frontend/src/scenes/billing/ConfirmUpgradeModal.tsxindex ea9e00096c69..d194d82fc5f7 100644--- a/frontend/src/scenes/billing/ConfirmUpgradeModal.tsx+++ b/frontend/src/scenes/billing/ConfirmUpgradeModal.tsx@@ -1,37 +1,35 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonModal, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'-import { dayjs } from 'lib/dayjs'import { billingLogic } from 'scenes/billing/billingLogic'import { billingProductLogic } from 'scenes/billing/billingProductLogic'import { BillingInvoiceItemRow, BillingProductV2AddonType } from '~/types'+import { ConfirmAddonChargeModal } from './ConfirmAddonChargeModal'++/**+ * Confirmation shown before switching from one platform add-on to another (e.g. Boost → Scale).+ * The prorated charge is offset by the unused time on the current add-on; ConfirmPurchaseModal is+ * the sibling that covers adding an add-on when there is nothing to switch from.+ */export function ConfirmUpgradeModal({ product }: { product: BillingProductV2AddonType }): JSX.Element | null {const { currentPlatformAddon, unusedPlatformAddonAmount, switchPlanLoading, billing } = useValues(billingLogic)- const { currentAndUpgradePlans, confirmUpgradeModalOpen, proratedAmount } = useValues(- billingProductLogic({ product })- )+ const { currentAndUpgradePlans, confirmUpgradeModalOpen, proratedAmount, appliedCreditBalance, amountDueToday } =+ useValues(billingProductLogic({ product }))const { hideConfirmUpgradeModal, confirmProductUpgrade } = useActions(billingProductLogic({ product }))- const isLoading = switchPlanLoading === product.type-const targetPlan = currentAndUpgradePlans?.upgradePlan- const amountDueBeforeCredits = Math.max(0, proratedAmount - unusedPlatformAddonAmount)- const availableCreditBalance = billing?.discount_amount_usd ? parseFloat(billing.discount_amount_usd) : 0- const appliedBalance = Math.min(amountDueBeforeCredits, availableCreditBalance)- const amountDue = Math.max(0, amountDueBeforeCredits - appliedBalance)-const periodEnd = billing?.billing_period?.current_period_end- const remainingPeriodFormatted = periodEnd- ? `${dayjs().format('MMM D')} - ${periodEnd.format('MMM D, YYYY')}`- : undefinedif (!confirmUpgradeModalOpen || !targetPlan || !currentPlatformAddon) {return null}+ const remainingPeriodFormatted = periodEnd+ ? `${dayjs().format('MMM D')} - ${periodEnd.format('MMM D, YYYY')}`+ : undefined+const rows: BillingInvoiceItemRow[] = [{description: `Remaining time on ${product.name}`,@@ -45,67 +43,30 @@ export function ConfirmUpgradeModal({ product }: { product: BillingProductV2Addo},]- if (appliedBalance > 0) {+ if (appliedCreditBalance > 0) {rows.push({description: 'Applied balance',- amount: `-$${appliedBalance.toFixed(2)}`,+ amount: `-$${appliedCreditBalance.toFixed(2)}`,})}rows.push({description: 'Amount due today',- amount: `$${amountDue.toFixed(2)}`,+ amount: `$${amountDueToday.toFixed(2)}`,isBold: true,})- const columns: LemonTableColumns<BillingInvoiceItemRow> = [- {- title: 'Description',- dataIndex: 'description',- render: (_, row) => (- <div className={`py-1 ${row.isBold ? 'font-bold' : 'font-medium'}`}>- <div>{row.description}</div>- {row.dateRange && <div className="text-muted text-xs">{row.dateRange}</div>}- </div>- ),- },- {- title: 'Amount',- dataIndex: 'amount',- align: 'right',- render: (_, row) => <div className={`py-1 ${row.isBold ? 'font-bold' : ''}`}>{row.amount}</div>,- },- ]-return (- <LemonModal- onClose={hideConfirmUpgradeModal}+ <ConfirmAddonChargeModalisOpen={confirmUpgradeModalOpen}- closable={false}- title={`Ready to subscribe to ${targetPlan.name}?`}- footer={- <>- <LemonButton- type="secondary"- onClick={hideConfirmUpgradeModal}- disabledReason={isLoading ? 'Subscription update in progress, do not close this modal' : ''}- >- Cancel- </LemonButton>- <LemonButton type="primary" onClick={confirmProductUpgrade} loading={isLoading}>- Confirm- </LemonButton>- </>- }- >- <div className="max-w-140">- <p>- You'll get access to all {product.name} features right away. ${amountDue.toFixed(2)} will be charged- now for the remaining period until {billing?.billing_period?.current_period_end?.format('MMM D')},- and ${targetPlan.unit_amount_usd} every {targetPlan.unit} thereafter.- </p>- <LemonTable dataSource={rows} columns={columns} className="mt-4" uppercaseHeader={false} />- </div>- </LemonModal>+ targetPlan={targetPlan}+ productName={product.name}+ isLoading={switchPlanLoading === product.type}+ rows={rows}+ amountDue={amountDueToday}+ periodEndLabel={periodEnd?.format('MMM D')}+ onCancel={hideConfirmUpgradeModal}+ onConfirm={confirmProductUpgrade}+ />)}diff --git a/frontend/src/scenes/billing/billingProductLogic.test.ts b/frontend/src/scenes/billing/billingProductLogic.test.tsnew file mode 100644index 000000000000..530abf7ea16f--- /dev/null+++ b/frontend/src/scenes/billing/billingProductLogic.test.ts@@ -0,0 +1,148 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { dayjs } from 'lib/dayjs'+// Imported from the source module rather than the `@posthog/lemon-ui` barrel so the spy below+// replaces `.error` on the same `lemonToast` singleton the logic calls at runtime (see the same+// note in paymentEntryLogic.test.ts).+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { billingLogic } from 'scenes/billing/billingLogic'+import { billingProductLogic } from 'scenes/billing/billingProductLogic'++import { defaultPlatformAddons } from '~/mocks/fixtures/_billing_platform_addons'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { BillingPlan, BillingProductV2AddonType, BillingType } from '~/types'++// Scale is a flat-rate platform add-on ($750/mo) — the exact shape that used to charge immediately.+const scaleAddon = defaultPlatformAddons.find((addon) => addon.type === BillingPlan.Scale) as BillingProductV2AddonType++const seedBilling = async (billing: Partial<BillingType>): Promise<void> => {+ useMocks({ get: { '/api/billing': () => [200, billing] } })+ billingLogic.mount()+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()+}++describe('billingProductLogic — confirm purchase modal', () => {+ let logic: ReturnType<typeof billingProductLogic.build>+ let toastErrorSpy: jest.SpyInstance++ beforeEach(async () => {+ initKeaTests()+ toastErrorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => ({ id: 'x' }) as any)+ // A card-on-file paying customer is the only one who reaches the flat-rate "Add" button.+ await seedBilling({ customer_id: 'cus_test', subscription_level: 'paid' })+ })++ afterEach(() => {+ logic?.unmount()+ toastErrorSpy.mockRestore()+ })++ it('opens and closes the modal via show/hide actions', async () => {+ logic = billingProductLogic({ product: scaleAddon })+ logic.mount()++ await expectLogic(logic, () => logic.actions.showConfirmPurchaseModal()).toMatchValues({+ confirmPurchaseModalOpen: true,+ })+ await expectLogic(logic, () => logic.actions.hideConfirmPurchaseModal()).toMatchValues({+ confirmPurchaseModalOpen: false,+ })+ })++ it('confirming the purchase activates the add-on with its upgrade plan', async () => {+ // Respond with an error so activation stops before any real-charge side effects, while still+ // proving the request fired with the right add-on + plan.+ const activate = jest.fn(() => [200, { success: false, error: 'stop before charge' }] as [number, unknown])+ useMocks({ post: { '/api/billing/activate': activate } })+ logic = billingProductLogic({ product: scaleAddon })+ logic.mount()++ await expectLogic(logic, () => logic.actions.confirmProductPurchase())+ .toDispatchActions([+ 'confirmProductPurchase',+ (a) =>+ a.type === logic.actionTypes.handleProductUpgrade &&+ a.payload.products === `${scaleAddon.type}:${scaleAddon.plans[0].plan_key}`,+ ])+ .toFinishAllListeners()++ expect(activate).toHaveBeenCalled()+ })++ it('auto-closes the modal once activation finishes', async () => {+ useMocks({+ post: { '/api/billing/activate': () => [200, { success: false, error: 'x' }] as [number, unknown] },+ })+ logic = billingProductLogic({ product: scaleAddon })+ logic.mount()+ logic.actions.showConfirmPurchaseModal()+ expect(logic.values.confirmPurchaseModalOpen).toBe(true)++ await expectLogic(logic, () => logic.actions.confirmProductPurchase())+ .toFinishAllListeners()+ .toMatchValues({ confirmPurchaseModalOpen: false })+ })++ describe('credit-aware amount selectors', () => {+ // Halfway through a billing period, so the $750 Scale plan prorates to ~$375.+ const seedBillingMidPeriod = async (discountAmountUsd?: string): Promise<void> => {+ await seedBilling({+ customer_id: 'cus_test',+ subscription_level: 'paid',+ products: [],+ discount_amount_usd: discountAmountUsd,+ // Dayjs values serialize to ISO strings in the mocked JSON response, which+ // billingLogic's parseBillingResponse turns back into Dayjs — same as the real API.+ billing_period: {+ current_period_start: dayjs().subtract(12, 'hour'),+ current_period_end: dayjs().add(12, 'hour'),+ interval: 'month',+ },+ })+ }++ it('applies the credit balance against the amount due', async () => {+ await seedBillingMidPeriod('100')+ logic = billingProductLogic({ product: scaleAddon })+ logic.mount()++ expect(logic.values.amountDueBeforeCredits).toBeCloseTo(375, 1)+ expect(logic.values.appliedCreditBalance).toBe(100)+ expect(logic.values.amountDueToday).toBeCloseTo(275, 1)+ })++ it('clamps the amount due at zero when the credit balance exceeds the charge', async () => {+ await seedBillingMidPeriod('1000')+ logic = billingProductLogic({ product: scaleAddon })+ logic.mount()++ // Only the amount due is applied — never more (no negative totals).+ expect(logic.values.appliedCreditBalance).toBeCloseTo(375, 1)+ expect(logic.values.appliedCreditBalance).toBe(logic.values.amountDueBeforeCredits)+ expect(logic.values.amountDueToday).toBe(0)+ })++ it('applies no credit when the customer has no balance', async () => {+ await seedBillingMidPeriod(undefined)+ logic = billingProductLogic({ product: scaleAddon })+ logic.mount()++ expect(logic.values.appliedCreditBalance).toBe(0)+ expect(logic.values.amountDueToday).toBe(logic.values.amountDueBeforeCredits)+ })+ })++ it('does nothing when the product has no upgrade plan', async () => {+ const activate = jest.fn(() => [200, { success: true }] as [number, unknown])+ useMocks({ post: { '/api/billing/activate': activate } })+ const productWithoutPlans = { ...scaleAddon, type: BillingPlan.Boost, plans: [] } as BillingProductV2AddonType+ logic = billingProductLogic({ product: productWithoutPlans })+ logic.mount()++ await expectLogic(logic, () => logic.actions.confirmProductPurchase()).toFinishAllListeners()++ expect(activate).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.tsindex cf0745031f08..eebe36749e06 100644--- a/frontend/src/scenes/billing/billingProductLogic.ts+++ b/frontend/src/scenes/billing/billingProductLogic.ts@@ -95,7 +95,12 @@ export interface billingProductLogicValues {timeRemainingInSeconds: number // billingLogictimeTotalInSeconds: number // billingLogicunsubscribeError: UnsubscribeError | null // billingLogic+ unusedPlatformAddonAmount: number // billingLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic+ amountDueBeforeCredits: number+ amountDueToday: number+ appliedCreditBalance: number+ availableCreditBalance: numberbillingGaugeItems: BillingGaugeItemType[]billingLimitAsUsage: numberbillingLimitConfig: BillingLimitConfig@@ -121,6 +126,7 @@ export interface billingProductLogicValues {combinedMonetaryGaugeItems: BillingGaugeItemType[]comparisonModalHighlightedFeatureKey: string | nullconfirmDowngradeModalOpen: boolean+ confirmPurchaseModalOpen: booleanconfirmUpgradeModalOpen: booleancurrentAmountTotalActual: stringcurrentAndUpgradePlans: {@@ -222,6 +228,9 @@ export interface billingProductLogicActions {confirmProductDowngrade: () => {value: true}+ confirmProductPurchase: () => {+ value: true+ }confirmProductUpgrade: () => {value: true}@@ -235,6 +244,9 @@ export interface billingProductLogicActions {hideConfirmDowngradeModal: () => {value: true}+ hideConfirmPurchaseModal: () => {+ value: true+ }hideConfirmUpgradeModal: () => {value: true}@@ -323,6 +335,9 @@ export interface billingProductLogicActions {showConfirmDowngradeModal: () => {value: true}+ showConfirmPurchaseModal: () => {+ value: true+ }showConfirmUpgradeModal: () => {value: true}@@ -391,6 +406,14 @@ export interface billingProductLogicMeta {billing: BillingType | null,product: BillingProductV2AddonType | BillingProductV2Type) => boolean+ availableCreditBalance: (billing: BillingType | null) => number+ amountDueBeforeCredits: (+ proratedAmount: number,+ unusedPlatformAddonAmount: number,+ isSubscribedToAnotherAddon: boolean+ ) => number+ appliedCreditBalance: (amountDueBeforeCredits: number, availableCreditBalance: number) => number+ amountDueToday: (amountDueBeforeCredits: number, appliedCreditBalance: number) => numbercustomLimitUsd: (billing: BillingType | null,product: BillingProductV2AddonType | BillingProductV2Type@@ -498,6 +521,7 @@ export const billingProductLogic = kea<billingProductLogicType>(['platformAddons','timeRemainingInSeconds','timeTotalInSeconds',+ 'unusedPlatformAddonAmount',],featureFlagLogic,['featureFlags'],@@ -566,6 +590,9 @@ export const billingProductLogic = kea<billingProductLogicType>([showConfirmDowngradeModal: true,hideConfirmDowngradeModal: true,confirmProductDowngrade: true,+ showConfirmPurchaseModal: true,+ hideConfirmPurchaseModal: true,+ confirmProductPurchase: true,}),reducers({billingLimitInput: [@@ -692,6 +719,16 @@ export const billingProductLogic = kea<billingProductLogicType>([hideConfirmDowngradeModal: () => false,},],+ confirmPurchaseModalOpen: [+ false as boolean,+ {+ showConfirmPurchaseModal: () => true,+ hideConfirmPurchaseModal: () => false,+ // Auto-close once the activation call settles (loading cleared), so the modal+ // doesn't linger if the purchase succeeds or routes to payment entry.+ setBillingProductLoading: (state, { productKey }) => (productKey ? state : false),+ },+ ],}),selectors(({ values }) => ({proratedAmount: [@@ -773,6 +810,31 @@ export const billingProductLogic = kea<billingProductLogicType>([return parentProduct.addons.some((a: BillingProductV2AddonType) => a.subscribed)},],+ // Single source of truth for what an add-on purchase/switch costs. Cards show+ // amountDueBeforeCredits (the price of the transaction); the confirmation modals+ // additionally itemize the credit balance and show amountDueToday (what hits the card).+ availableCreditBalance: [+ (s) => [s.billing],+ (billing: BillingType | null): number =>+ billing?.discount_amount_usd ? parseFloat(billing.discount_amount_usd) : 0,+ ],+ amountDueBeforeCredits: [+ (s) => [s.proratedAmount, s.unusedPlatformAddonAmount, s.isSubscribedToAnotherAddon],+ (proratedAmount: number, unusedPlatformAddonAmount: number, isSubscribedToAnotherAddon: boolean): number =>+ // Unused time on the current platform add-on only offsets a switch to another+ // one; a fresh purchase has nothing to trade in.+ Math.max(0, proratedAmount - (isSubscribedToAnotherAddon ? unusedPlatformAddonAmount : 0)),+ ],+ appliedCreditBalance: [+ (s) => [s.amountDueBeforeCredits, s.availableCreditBalance],+ (amountDueBeforeCredits: number, availableCreditBalance: number): number =>+ Math.min(amountDueBeforeCredits, availableCreditBalance),+ ],+ amountDueToday: [+ (s) => [s.amountDueBeforeCredits, s.appliedCreditBalance],+ (amountDueBeforeCredits: number, appliedCreditBalance: number): number =>+ Math.max(0, amountDueBeforeCredits - appliedCreditBalance),+ ],customLimitUsd: [(s, p) => [s.billing, p.product],(billing: BillingType | null, product: BillingProductV2AddonType | BillingProductV2Type) => {@@ -1164,6 +1226,16 @@ export const billingProductLogic = kea<billingProductLogicType>([to_plan_key: String(upgradePlan.plan_key),})},+ confirmProductPurchase: () => {+ const upgradePlan = values.currentAndUpgradePlans.upgradePlan+ if (!upgradePlan) {+ return+ }+ // Fresh flat-rate add-on purchase (nothing to switch from). Fire the same activation+ // the "Add" button used to trigger directly — now gated behind the confirmation modal+ // so a card-on-file customer sees what they'll be charged before it happens.+ actions.initiateProductUpgrade(props.product, upgradePlan, '')+ },confirmProductDowngrade: () => {const targetPlan = values.currentAndUpgradePlans.upgradePlanconst currentPlatformAddon = values.currentPlatformAddon