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.

feat(billing): show companion products on their parent's card (#114321)

Roy Cohen5837ca16461e
diff --git a/ee/billing/billing_types.py b/ee/billing/billing_types.py
index 774aed26881f..147648a59616 100644
--- a/ee/billing/billing_types.py
+++ b/ee/billing/billing_types.py
@@ -149,6 +149,8 @@ class CustomerProduct(TypedDict):
addons: list[CustomerProductAddon]
# Billing refuses a customer billing limit for this product. Older billing omits the key.
no_billing_limit: NotRequired[bool]
+ # Set on a companion product: the type of the product it is billed under. Older billing omits the key.
+ companion_of: NotRequired[Optional[str]]
class LicenseInfo(TypedDict):
diff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsx
index 5d883a76dc6e..45602b087c67 100644
--- a/frontend/src/scenes/billing/Billing.tsx
+++ b/frontend/src/scenes/billing/Billing.tsx
@@ -28,6 +28,7 @@ import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
import { BillingProductV2Type } from '~/types'
+import { isCompanionProduct } from './billing-utils'
import { BillingHero } from './BillingHero'
import { billingLogic } from './billingLogic'
import { BillingNoAccess } from './BillingNoAccess'
@@ -260,7 +261,8 @@ export function Billing(): JSX.Element {
)
?.filter(
(product: BillingProductV2Type) =>
- !product.inclusion_only || product.addons.find((a) => !a.inclusion_only)
+ !isCompanionProduct(product) &&
+ (!product.inclusion_only || product.addons.find((a) => !a.inclusion_only))
)
?.map((x: BillingProductV2Type) => (
<div key={x.type}>
diff --git a/frontend/src/scenes/billing/BillingCompanionSection.test.tsx b/frontend/src/scenes/billing/BillingCompanionSection.test.tsx
new file mode 100644
index 000000000000..16c1ff0c3c17
--- /dev/null
+++ b/frontend/src/scenes/billing/BillingCompanionSection.test.tsx
@@ -0,0 +1,345 @@
+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { billingJson } from '~/mocks/fixtures/_billing'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { BillingProductV2Type, BillingType } from '~/types'
+
+import { Billing } from './Billing'
+import { BillingCompanionSection } from './BillingCompanionSection'
+import { billingLogic } from './billingLogic'
+import { BillingProduct } from './BillingProduct'
+import { PlanComparison } from './PlanComparison'
+
+const replay = billingJson.products.find((p) => p.type === 'session_replay') as BillingProductV2Type
+const productAnalytics = billingJson.products.find((p) => p.type === 'product_analytics') as BillingProductV2Type
+
+const logs: BillingProductV2Type = {
+ ...replay,
+ type: 'logs',
+ name: 'Logs',
+ current_amount_usd: '100.00',
+ projected_amount_usd: '200.00',
+ projected_amount_usd_with_limit: '200.00',
+}
+
+const customRetention = ({ subscribed = true, onCurrentPlan = true } = {}): BillingProductV2Type => ({
+ ...replay,
+ type: 'logs_retention_custom',
+ name: 'Logs custom retention',
+ companion_of: 'logs',
+ inclusion_only: true,
+ no_billing_limit: true,
+ addons: [],
+ usage_limit: null,
+ subscribed,
+ plans: replay.plans.map((plan) => ({ ...plan, current_plan: onCurrentPlan })),
+ current_amount_usd: '12.50',
+ projected_amount_usd: '30.25',
+})
+
+const limitedCompanion: BillingProductV2Type = {
+ ...customRetention(),
+ type: 'logs_limited_extra',
+ name: 'Logs limited extra',
+ no_billing_limit: undefined,
+ current_amount_usd: '40.00',
+ projected_amount_usd: '80.00',
+}
+
+const otherNoLimitCompanion: BillingProductV2Type = {
+ ...customRetention(),
+ type: 'logs_other_extra',
+ name: 'Logs other extra',
+ current_amount_usd: '5.00',
+ projected_amount_usd: '10.00',
+}
+
+const setCustomRetentionHidden = (hidden: boolean): void => {
+ const flag = 'billing_hide_product_logs_retention_custom'
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags(hidden ? [flag] : [], { [flag]: hidden })
+}
+
+const seedBilling = async (products: BillingProductV2Type[], overrides: Partial<BillingType> = {}): Promise<void> => {
+ useMocks({ get: { '/api/billing': () => [200, { ...billingJson, ...overrides, products }] } })
+ billingLogic.mount()
+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()
+}
+
+const renderSection = (product: BillingProductV2Type): void => {
+ render(
+ <Provider>
+ <BillingCompanionSection product={product} cardShowsBillingLimit cardShowsProjection />
+ </Provider>
+ )
+}
+
+describe('BillingCompanionSection', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ localStorage.clear()
+ })
+
+ it('shows a held companion with its amounts and a total that adds it to the parent', async () => {
+ await seedBilling([logs, customRetention()])
+ renderSection(logs)
+
+ expect(screen.getByText('Not covered by your billing limit')).toBeInTheDocument()
+ expect(screen.getByText('Your Logs billing limit does not cap these charges.')).toBeInTheDocument()
+ const row = screen.getByTestId('billing-companion-logs_retention_custom')
+ expect(row).toHaveTextContent('Custom retention')
+ expect(row).toHaveTextContent('$12.50Month-to-date')
+ expect(row).toHaveTextContent('$30.25Projected')
+ const total = screen.getByTestId('billing-companions-total-logs')
+ expect(total).toHaveTextContent('Total including this section: $112.50 month-to-date, $230.25 projected')
+ expect(within(total).getByText('$112.50')).toHaveAttribute('translate', 'no')
+ expect(within(total).getByText('$230.25')).toHaveAttribute('translate', 'no')
+
+ await userEvent.click(screen.getByLabelText('Show Custom retention details'))
+ expect(screen.getByLabelText('Hide Custom retention details')).toBeInTheDocument()
+ expect(row.querySelector('.LemonTable')).toBeInTheDocument()
+ })
+
+ it('renders nothing when the parent holds no companion', async () => {
+ await seedBilling([logs, customRetention({ subscribed: false, onCurrentPlan: false })])
+ const { container } = render(
+ <Provider>
+ <BillingCompanionSection product={logs} cardShowsBillingLimit cardShowsProjection />
+ </Provider>
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('renders nothing for a held companion that can have its own billing limit', async () => {
+ await seedBilling([logs, limitedCompanion])
+ const { container } = render(
+ <Provider>
+ <BillingCompanionSection product={logs} cardShowsBillingLimit cardShowsProjection />
+ </Provider>
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ it('shows and totals only the companion that cannot have a billing limit', async () => {
+ await seedBilling([logs, customRetention(), limitedCompanion])
+ renderSection(logs)
+
+ expect(screen.getByTestId('billing-companion-logs_retention_custom')).toBeInTheDocument()
+ expect(screen.queryByTestId('billing-companion-logs_limited_extra')).not.toBeInTheDocument()
+ expect(screen.getByTestId('billing-companions-total-logs')).toHaveTextContent(
+ 'Total including this section: $112.50 month-to-date, $230.25 projected'
+ )
+ })
+
+ it('totals the parent at its projection capped by the billing limit', async () => {
+ const cappedLogs = { ...logs, projected_amount_usd: '500.00', projected_amount_usd_with_limit: '200.00' }
+ await seedBilling([cappedLogs, customRetention()])
+ renderSection(cappedLogs)
+
+ expect(screen.getByTestId('billing-companions-total-logs')).toHaveTextContent(
+ 'Total including this section: $112.50 month-to-date, $230.25 projected'
+ )
+ })
+
+ it.each([
+ {
+ name: 'the parent is not subscribed and the companion is stale',
+ parent: { ...logs, subscribed: false },
+ companion: customRetention({ subscribed: false }),
+ billingPeriod: { ...billingJson.billing_period!, interval: 'month' as const },
+ rowLabel: '$12.50Month-to-date',
+ totals: [],
+ },
+ {
+ name: 'the plan bills yearly',
+ parent: logs,
+ companion: customRetention(),
+ billingPeriod: { ...billingJson.billing_period!, interval: 'year' as const },
+ rowLabel: '$12.50Year-to-date',
+ totals: ['Total including this section: $112.50 year-to-date, $230.25 projected'],
+ },
+ {
+ name: 'the parent has no billing limit',
+ parent: { ...logs, no_billing_limit: true },
+ companion: customRetention(),
+ billingPeriod: { ...billingJson.billing_period!, interval: 'month' as const },
+ rowLabel: '$12.50Month-to-date',
+ totals: ['Total including this section: $112.50 month-to-date, $230.25 projected'],
+ },
+ ])(
+ 'keeps the rows for the billing interval but drops the limit sentence when $name',
+ async ({ parent, companion, billingPeriod, rowLabel, totals }) => {
+ await seedBilling([parent, companion], { billing_period: billingPeriod })
+ renderSection(parent)
+
+ expect(screen.getByText('Not covered by your billing limit')).toBeInTheDocument()
+ expect(screen.getByTestId('billing-companion-logs_retention_custom')).toHaveTextContent(rowLabel)
+ expect(screen.queryByText(/billing limit does not cap these charges/)).not.toBeInTheDocument()
+ expect(
+ screen
+ .queryAllByTestId('billing-companions-total-logs')
+ .map((total) => total.textContent?.replace(/\s+/g, ' '))
+ ).toEqual(totals)
+ }
+ )
+
+ it('adds the companion rows to the header amounts of a parent without variants', async () => {
+ const analytics = {
+ ...productAnalytics,
+ current_amount_usd: '40.10',
+ projected_amount_usd_with_limit: '960.00',
+ }
+ const analyticsCompanion: BillingProductV2Type = {
+ ...customRetention(),
+ type: 'analytics_extra',
+ name: 'Analytics extra',
+ companion_of: 'product_analytics',
+ current_amount_usd: '12.50',
+ projected_amount_usd: '30.20',
+ }
+ await seedBilling([analytics, analyticsCompanion], { discount_percent: 10 })
+ render(
+ <Provider>
+ <BillingProduct product={analytics} />
+ </Provider>
+ )
+
+ // 10% off: header $36.09 + $864.00, companion $11.25 + $27.18.
+ const card = screen.getByTestId('billing-product-product_analytics')
+ expect(within(card).getByText('$36.09')).toBeInTheDocument()
+ expect(within(card).getByText('$864.00')).toBeInTheDocument()
+ const row = screen.getByTestId('billing-companion-analytics_extra')
+ expect(row).toHaveTextContent('$11.25Month-to-date')
+ expect(row).toHaveTextContent('$27.18Projected')
+ expect(screen.getByTestId('billing-companions-total-product_analytics')).toHaveTextContent(
+ 'Total including this section: $47.34 month-to-date, $891.18 projected'
+ )
+ })
+
+ it('drops the limit sentence when the card hides its billing limit for a temporary free product', async () => {
+ const freeLogs: BillingProductV2Type = { ...logs, addons: [], tiers: [{ ...replay.tiers![0], up_to: null }] }
+ await seedBilling([freeLogs, customRetention()])
+ render(
+ <Provider>
+ <BillingProduct product={freeLogs} />
+ </Provider>
+ )
+
+ expect(screen.getByText('included with your plan')).toBeInTheDocument()
+ expect(screen.queryByTestId('billing-limit-input-wrapper-logs')).not.toBeInTheDocument()
+ expect(screen.getByText('Not covered by your billing limit')).toBeInTheDocument()
+ expect(screen.getByTestId('billing-companion-logs_retention_custom')).toHaveTextContent('$12.50Month-to-date')
+ expect(screen.queryByText(/billing limit does not cap these charges/)).not.toBeInTheDocument()
+ expect(screen.queryByTestId('billing-companions-total-logs')).not.toBeInTheDocument()
+ })
+
+ it('drops the total line when the card shows a flat price instead of month-to-date and projected', async () => {
+ const flatLogs: BillingProductV2Type = { ...logs, addons: [], tiered: false, tiers: null }
+ await seedBilling([flatLogs, customRetention()])
+ render(
+ <Provider>
+ <BillingProduct product={flatLogs} />
+ </Provider>
+ )
+
+ const card = screen.getByTestId('billing-product-logs')
+ expect(within(card).getByText('$100.00')).toBeInTheDocument()
+ expect(within(card).getByText('per month')).toBeInTheDocument()
+ expect(screen.getByTestId('billing-companion-logs_retention_custom')).toHaveTextContent('$12.50Month-to-date')
+ expect(screen.queryByTestId('billing-companions-total-logs')).not.toBeInTheDocument()
+ })
+
+ it('sits on the parent card after the billing limit', async () => {
+ await seedBilling([logs, customRetention()])
+ render(
+ <Provider>
+ <BillingProduct product={logs} />
+ </Provider>
+ )
+
+ const limit = screen.getByTestId('billing-limit-input-wrapper-logs')
+ const section = screen.getByTestId('billing-companions-logs')
+ expect(screen.getByTestId('billing-product-logs')).toContainElement(section)
+ expect(limit.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ })
+
+ it.each([
+ {
+ hidden: true,
+ rows: ['billing-companion-logs_other_extra'],
+ total: 'Total including this section: $105.00 month-to-date, $210.00 projected',
+ },
+ {
+ hidden: false,
+ rows: ['billing-companion-logs_retention_custom', 'billing-companion-logs_other_extra'],
+ total: 'Total including this section: $117.50 month-to-date, $240.25 projected',
+ },
+ ])(
+ 'shows and totals a companion only when its billing_hide_product flag is off (hidden: $hidden)',
+ async ({ hidden, rows, total }) => {
+ setCustomRetentionHidden(hidden)
+ await seedBilling([logs, customRetention(), otherNoLimitCompanion])
+ renderSection(logs)
+
+ expect(
+ screen.getAllByTestId(/^billing-companion-logs_/).map((row) => row.getAttribute('data-attr'))
+ ).toEqual(rows)
+ expect(screen.getByTestId('billing-companions-total-logs')).toHaveTextContent(total)
+ }
+ )
+
+ it('renders nothing when the billing_hide_product flag hides the only companion', async () => {
+ setCustomRetentionHidden(true)
+ await seedBilling([logs, customRetention()])
+ const { container } = render(
+ <Provider>
+ <BillingCompanionSection product={logs} cardShowsBillingLimit cardShowsProjection />
+ </Provider>
+ )
+
+ expect(container).toBeEmptyDOMElement()
+ })
+
+ describe('a companion outside its parent card', () => {
+ it('never gets its own product card, even when it is not inclusion-only', async () => {
+ await seedBilling([logs, { ...customRetention(), inclusion_only: false }])
+ render(
+ <Provider>
+ <Billing />
+ </Provider>
+ )
+
+ expect(await screen.findByTestId('billing-product-logs')).toBeInTheDocument()
+ expect(screen.queryByTestId('billing-product-logs_retention_custom')).not.toBeInTheDocument()
+ })
+
+ it('is left out of the included platform features in the plan comparison', async () => {
+ const integrations = billingJson.products.find((p) => p.type === 'integrations') as BillingProductV2Type
+ await seedBilling([productAnalytics, integrations, customRetention()], { has_active_subscription: false })
+ render(
+ <Provider>
+ <PlanComparison product={productAnalytics} />
+ </Provider>
+ )
+
+ expect(screen.getByText('Included platform features:')).toBeInTheDocument()
+ expect(screen.getByText('Integrations')).toBeInTheDocument()
+ expect(screen.queryByText('Logs custom retention')).not.toBeInTheDocument()
+ })
+ })
+})
diff --git a/frontend/src/scenes/billing/BillingCompanionSection.tsx b/frontend/src/scenes/billing/BillingCompanionSection.tsx
new file mode 100644
index 000000000000..efee0d244335
--- /dev/null
+++ b/frontend/src/scenes/billing/BillingCompanionSection.tsx
@@ -0,0 +1,99 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+
+import { BillingProductV2Type } from '~/types'
+
+import { createGaugeItems, isBillingLimitShown } from './billing-utils'
+import { BillingGauge } from './BillingGauge'
+import { billingLogic } from './billingLogic'
+import { billingProductDisplayName, billingProductRowDisplayName } from './billingProductDisplayName'
+import { billingProductLogic } from './billingProductLogic'
+import { BillingProductPricingTable } from './BillingProductPricingTable'
+
+// Companions bill under the parent card but outside its billing limit, so the card's own amounts leave them out.
+// The parent card says whether its layout has the limit block and a projected amount, so the section mentions only those.
+export const BillingCompanionSection = ({
+ product,
+ cardShowsBillingLimit,
+ cardShowsProjection,
+}: {
+ product: BillingProductV2Type
+ cardShowsBillingLimit: boolean
+ cardShowsProjection: boolean
+}): JSX.Element | null => {
+ const { billing, isUnlicensedDebug } = useValues(billingLogic)
+ const { noLimitCompanionAmounts, totalsIncludingCompanions, variantExpandedStates } = useValues(
+ billingProductLogic({ product })
+ )
+ const { toggleVariantExpanded } = useActions(billingProductLogic({ product }))
+
+ if (isUnlicensedDebug || noLimitCompanionAmounts.length === 0) {
+ return null
+ }
+
+ const periodLabel = `${billing?.billing_period?.interval || 'month'}-to-date`
+
+ return (
+ <div className="border-t border-primary px-8 py-4" data-attr={`billing-companions-${product.type}`}>
+ <h4 className="mb-0">Not covered by your billing limit</h4>
+ {cardShowsBillingLimit && isBillingLimitShown(product, billing) && (
+ <p className="text-sm text-secondary mb-0">
+ Your {billingProductDisplayName(product)} billing limit does not cap these charges.
+ </p>
+ )}
+ <div className="space-y-4 mt-4">
+ {noLimitCompanionAmounts.map(({ companion, currentAmount, projectedAmount }) => {
+ const isExpanded = !!variantExpandedStates?.[companion.type]
+ const displayName = billingProductRowDisplayName(companion)
+ return (
+ <div key={companion.type} data-attr={`billing-companion-${companion.type}`}>
+ <div className="grid grid-cols-[auto_1fr_130px_100px] gap-4 items-center">
+ <LemonButton
+ icon={isExpanded ? <IconChevronDown /> : <IconChevronRight />}
+ size="small"
+ aria-label={`${isExpanded ? 'Hide' : 'Show'} ${displayName} details`}
+ onClick={() => toggleVariantExpanded(companion.type)}
+ />
+ <h4 className="mb-0 font-bold">{displayName}</h4>
+ <div className="flex flex-col items-end">
+ <span className="font-bold text-lg leading-5">
+ {humanFriendlyCurrency(currentAmount)}
+ </span>
+ <span className="text-xs text-secondary">{capitalizeFirstLetter(periodLabel)}</span>
+ </div>
+ <div className="flex flex-col items-end">
+ <span className="text-secondary text-lg leading-5">
+ {humanFriendlyCurrency(projectedAmount)}
+ </span>
+ <span className="text-xs text-secondary">Projected</span>
+ </div>
+ </div>
+ {isExpanded && (
+ <div className="mt-4">
+ <div className="ml-16">
+ <BillingGauge items={createGaugeItems(companion)} product={companion} />
+ </div>
+ <BillingProductPricingTable product={companion} />
+ </div>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ {product.subscribed && cardShowsProjection && (
+ <p className="text-sm mt-4 mb-0" data-attr={`billing-companions-total-${product.type}`}>
+ <span>Total including this section:&nbsp;</span>
+ <span translate="no">{humanFriendlyCurrency(totalsIncludingCompanions.currentTotal)}</span>
+ <span>{`\u00a0${periodLabel},\u00a0`}</span>
+ <span translate="no">{humanFriendlyCurrency(totalsIncludingCompanions.projectedTotal)}</span>
+ <span>&nbsp;projected</span>
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/billing/BillingLimit.tsx b/frontend/src/scenes/billing/BillingLimit.tsx
index 7b688117fdbc..1c7c22a781b9 100644
--- a/frontend/src/scenes/billing/BillingLimit.tsx
+++ b/frontend/src/scenes/billing/BillingLimit.tsx
@@ -9,7 +9,7 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { BillingProductV2Type } from '~/types'
-import { canHaveBillingLimit } from './billing-utils'
+import { isBillingLimitShown } from './billing-utils'
import { billingLogic } from './billingLogic'
import { billingProductDisplayName } from './billingProductDisplayName'
import { billingProductLogic } from './billingProductLogic'
@@ -33,12 +33,7 @@ export const BillingLimit = ({ product }: { product: BillingProductV2Type }): JS
const usingInitialBillingLimit = customLimitUsd === initialBillingLimit
const hasBillingLimitNextPeriod = billingLimitNextPeriod !== null
- if (
- billing?.billing_period?.interval !== 'month' ||
- !product.subscribed ||
- product.inclusion_only ||
- !canHaveBillingLimit(product)
- ) {
+ if (!isBillingLimitShown(product, billing)) {
return null
}
diff --git a/frontend/src/scenes/billing/BillingProduct.tsx b/frontend/src/scenes/billing/BillingProduct.tsx
index 5952e1e4406d..326da0d81d2a 100644
--- a/frontend/src/scenes/billing/BillingProduct.tsx
+++ b/frontend/src/scenes/billing/BillingProduct.tsx
@@ -27,6 +27,7 @@ import {
isUsageAtOrOverLimit,
isProductVariantPrimary,
} from './billing-utils'
+import { BillingCompanionSection } from './BillingCompanionSection'
import { BillingGauge } from './BillingGauge'
import { BillingLimit } from './BillingLimit'
import { billingLogic } from './billingLogic'
@@ -588,6 +589,13 @@ export const BillingProduct = ({ product }: { product: BillingProductV2Type }):
</div>
)}
+ <BillingCompanionSection
+ product={product}
+ cardShowsBillingLimit={!isTemporaryFreeProduct}
+ // Same branches as the header: the variants' combined amounts or the usage-priced (tiered) layout.
+ cardShowsProjection={isProductWithVariants || (!isTemporaryFreeProduct && product.tiered)}
+ />
+
{/* Feature flag usage notice */}
<FeatureFlagUsageNotice product={product} />
</div>
diff --git a/frontend/src/scenes/billing/PlanComparison.tsx b/frontend/src/scenes/billing/PlanComparison.tsx
index 4ae3045b0eba..3b30dda80cd2 100644
--- a/frontend/src/scenes/billing/PlanComparison.tsx
+++ b/frontend/src/scenes/billing/PlanComparison.tsx
@@ -21,7 +21,7 @@ import {
BillingProductV2Type,
} from '~/types'
-import { convertLargeNumberToWords, getProration } from './billing-utils'
+import { convertLargeNumberToWords, getProration, isCompanionProduct } from './billing-utils'
import { billingLogic } from './billingLogic'
import { billingProductLogic } from './billingProductLogic'
import { UnsubscribeSurveyModal } from './UnsubscribeSurveyModal'
@@ -364,7 +364,7 @@ export const PlanComparison = ({
</th>
</tr>
{billing?.products
- .filter((product) => product.inclusion_only)
+ .filter((product) => product.inclusion_only && !isCompanionProduct(product))
.map((includedProduct) => {
const includedPlans = includedProduct.plans.filter(
(plan) => plan.included_if == 'has_subscription' || plan.current_plan
diff --git a/frontend/src/scenes/billing/billing-companions.test.ts b/frontend/src/scenes/billing/billing-companions.test.ts
new file mode 100644
index 000000000000..2be15b57e862
--- /dev/null
+++ b/frontend/src/scenes/billing/billing-companions.test.ts
@@ -0,0 +1,54 @@
+import { billingJson } from '~/mocks/fixtures/_billing'
+import { BillingProductV2Type } from '~/types'
+
+import { getHeldCompanions, isCompanionHeld, isCompanionProduct } from './billing-utils'
+
+describe('companion products', () => {
+ const productAnalytics = billingJson.products.find((p) => p.type === 'product_analytics') as BillingProductV2Type
+ const plansWithCurrent = (current: boolean): BillingProductV2Type['plans'] =>
+ productAnalytics.plans.map((plan) => ({ ...plan, current_plan: current }))
+ const companion = (
+ type: string,
+ companionOf: string,
+ state: { subscribed: boolean; onCurrentPlan: boolean }
+ ): BillingProductV2Type => ({
+ ...productAnalytics,
+ type,
+ companion_of: companionOf,
+ inclusion_only: true,
+ no_billing_limit: true,
+ addons: [],
+ usage_limit: null,
+ subscribed: state.subscribed,
+ plans: plansWithCurrent(state.onCurrentPlan),
+ })
+
+ it.each([
+ ['a companion', 'logs', true],
+ ['a product without companion_of', undefined, false],
+ ['a product with a null companion_of', null, false],
+ ])('isCompanionProduct recognizes %s', (_name, companionOf, expected) => {
+ expect(isCompanionProduct({ ...productAnalytics, companion_of: companionOf })).toBe(expected)
+ })
+
+ it.each([
+ ['a subscribed companion', { subscribed: true, onCurrentPlan: false }, true],
+ ['an unsubscribed companion still on its plan', { subscribed: false, onCurrentPlan: true }, true],
+ ['a companion the customer does not hold', { subscribed: false, onCurrentPlan: false }, false],
+ ])('isCompanionHeld counts %s', (_name, state, expected) => {
+ expect(isCompanionHeld(companion('logs_retention_custom', 'logs', state))).toBe(expected)
+ })
+
+ it('getHeldCompanions returns only the held companions of the given parent', () => {
+ const held = companion('logs_retention_custom', 'logs', { subscribed: true, onCurrentPlan: true })
+ const stale = companion('logs_extra', 'logs', { subscribed: false, onCurrentPlan: true })
+ const notHeld = companion('logs_other', 'logs', { subscribed: false, onCurrentPlan: false })
+ const otherParent = companion('replay_extra', 'session_replay', { subscribed: true, onCurrentPlan: true })
+
+ expect(
+ getHeldCompanions([productAnalytics, held, stale, notHeld, otherParent], 'logs').map((p) => p.type)
+ ).toEqual(['logs_retention_custom', 'logs_extra'])
+ expect(getHeldCompanions([productAnalytics, notHeld, otherParent], 'logs')).toEqual([])
+ expect(getHeldCompanions(undefined, 'logs')).toEqual([])
+ })
+})
diff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.ts
index c6004f90ae42..a4d45fb53102 100644
--- a/frontend/src/scenes/billing/billing-utils.ts
+++ b/frontend/src/scenes/billing/billing-utils.ts
@@ -46,6 +46,26 @@ export const calculateFreeTier = (product: BillingProductV2Type | BillingProduct
export const canHaveBillingLimit = (product: BillingProductV2Type | BillingProductV2AddonType): boolean =>
!('no_billing_limit' in product && product.no_billing_limit === true)
+// Whether the product card shows its billing limit block.
+export const isBillingLimitShown = (product: BillingProductV2Type, billing: BillingType | null): boolean =>
+ billing?.billing_period?.interval === 'month' &&
+ !!product.subscribed &&
+ !product.inclusion_only &&
+ canHaveBillingLimit(product)
+
+export const isCompanionProduct = (product: BillingProductV2Type): boolean => !!product.companion_of
+
+// After the parent leaves a priced plan, billing keeps the companion on its plan with `subscribed: false`,
+// and it still bills.
+export const isCompanionHeld = (product: BillingProductV2Type): boolean =>
+ !!product.subscribed || !!product.plans?.some((plan) => plan.current_plan)
+
+export const getHeldCompanions = (
+ products: BillingProductV2Type[] | null | undefined,
+ parentType: string
+): BillingProductV2Type[] =>
+ products?.filter((product) => product.companion_of === parentType && isCompanionHeld(product)) ?? []
+
export const createGaugeItems = (
product: BillingProductV2Type | BillingProductV2AddonType,
options: {
diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.ts
index cd045275f1d2..9dfc639cf667 100644
--- a/frontend/src/scenes/billing/billingLogic.test.ts
+++ b/frontend/src/scenes/billing/billingLogic.test.ts
@@ -257,6 +257,32 @@ describe('billingLogic', () => {
}
)
+ // A companion has no billing limit, so its usage percentage must not raise a limit banner.
+ it.each([
+ ['reached', 1.5],
+ ['approaching', 0.9],
+ ])('raises no %s usage limit banner for a companion', async (_name, percentageUsage) => {
+ billingState = billingWithProducts([
+ productWithUsage(0),
+ productWithUsage(percentageUsage, {
+ type: 'logs_retention_custom',
+ usage_key: 'logs_retention_custom_gb_months',
+ name: 'Logs custom retention',
+ companion_of: 'logs',
+ inclusion_only: true,
+ no_billing_limit: true,
+ }),
+ ])
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(billingLogic.values.billingAlert).toBeNull()
+ })
+
it('clears a stale usage limit alert when refreshed billing data no longer qualifies', async () => {
billingState = billingWithProducts([productWithUsage(1)])
billingLogic.mount()
diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsx
index 34a3b5706c6c..3907902326ac 100644
--- a/frontend/src/scenes/billing/billingLogic.tsx
+++ b/frontend/src/scenes/billing/billingLogic.tsx
@@ -43,6 +43,7 @@ import {
canViewUsageAndSpend as canViewUsageAndSpendUtil,
getMinimumBillingAccessLevel,
getMinimumUsageSpendReadAccessLevel,
+ isCompanionProduct,
isUsageApproachingLimit,
isUsageAtOrOverLimit,
isMemberUsageSpendReadAccessEnabled,
@@ -1623,7 +1624,8 @@ export const billingLogic = kea<billingLogicType>([
const productsAtOrOverLimit =
values.billing.products?.filter((x: BillingProductV2Type) => {
- if (!isUsageAtOrOverLimit(x.percentage_usage) || !x.usage_key) {
+ // 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}`
@@ -1669,7 +1671,10 @@ export const billingLogic = kea<billingLogicType>([
const productsApproachingLimit =
values.billing.products?.filter((x: BillingProductV2Type) => {
- if (!isUsageApproachingLimit(x.percentage_usage, ALLOCATION_THRESHOLD_ALERT)) {
+ if (
+ !isUsageApproachingLimit(x.percentage_usage, ALLOCATION_THRESHOLD_ALERT) ||
+ isCompanionProduct(x)
+ ) {
return false
}
const hideProductFlag = `billing_hide_product_${x.type}`
diff --git a/frontend/src/scenes/billing/billingProductDisplayName.ts b/frontend/src/scenes/billing/billingProductDisplayName.ts
index bd179b02a756..c06133df93f3 100644
--- a/frontend/src/scenes/billing/billingProductDisplayName.ts
+++ b/frontend/src/scenes/billing/billingProductDisplayName.ts
@@ -12,3 +12,17 @@ const DISPLAY_NAME_BY_PRODUCT_TYPE: Record<string, string> = {
export function billingProductDisplayName(product: { type?: string | null; name: string }): string {
return (product.type && DISPLAY_NAME_BY_PRODUCT_TYPE[product.type]) || product.name
}
+
+// Names for the rows inside a product card: its variants and its companions.
+const ROW_DISPLAY_NAME_BY_PRODUCT_TYPE: Record<string, string> = {
+ session_replay: 'Web session replay',
+ data_warehouse: 'Synced rows',
+ data_warehouse_historical: 'Free historical synced rows',
+ logs: 'Logs ingestion (14-day retention)',
+ logs_retention_30d: '30-day retention',
+ logs_retention_custom: 'Custom retention',
+}
+
+export function billingProductRowDisplayName(product: { type?: string | null; name: string }): string {
+ return (product.type && ROW_DISPLAY_NAME_BY_PRODUCT_TYPE[product.type]) || product.name
+}
diff --git a/frontend/src/scenes/billing/billingProductLogic.test.ts b/frontend/src/scenes/billing/billingProductLogic.test.ts
index 8906088d5dbf..45a9d2f89708 100644
--- a/frontend/src/scenes/billing/billingProductLogic.test.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.test.ts
@@ -163,6 +163,109 @@ describe('billingProductLogic', () => {
})
})
+ describe('companions', () => {
+ const replay = productByType('session_replay')
+ const logs: BillingProductV2Type = {
+ ...replay,
+ type: 'logs',
+ name: 'Logs',
+ current_amount_usd: '100.00',
+ projected_amount_usd_with_limit: '200.00',
+ }
+ const companion = (type: string, companionOf: string, held: boolean): BillingProductV2Type => ({
+ ...replay,
+ type,
+ companion_of: companionOf,
+ inclusion_only: true,
+ no_billing_limit: true,
+ addons: [],
+ usage_limit: null,
+ subscribed: held,
+ plans: replay.plans.map((plan) => ({ ...plan, current_plan: false })),
+ current_amount_usd: '10.00',
+ projected_amount_usd: '20.00',
+ })
+
+ const seedProducts = async (products: BillingProductV2Type[], discountPercent?: number): Promise<void> => {
+ useMocks({
+ get: {
+ '/api/billing': () => [200, { ...billingJson, products, discount_percent: discountPercent }],
+ },
+ })
+ billingLogic.mount()
+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()
+ }
+
+ const mountLogs = (product: BillingProductV2Type = logs): ReturnType<typeof billingProductLogic.build> => {
+ const logic = billingProductLogic({ product })
+ logic.mount()
+ mounted.push(logic)
+ return logic
+ }
+
+ it('lists only the held companions of this parent', async () => {
+ await seedProducts([
+ logs,
+ companion('logs_retention_custom', 'logs', true),
+ companion('logs_not_held', 'logs', false),
+ companion('replay_companion', 'session_replay', true),
+ ])
+
+ expect(mountLogs().values.heldCompanions.map((p) => p.type)).toEqual(['logs_retention_custom'])
+ })
+
+ it('lists nothing when the parent holds no companion', async () => {
+ await seedProducts([logs, companion('logs_not_held', 'logs', false)])
+
+ expect(mountLogs().values.heldCompanions).toEqual([])
+ })
+
+ it('totals the header amounts and the held companions after the discount', async () => {
+ await seedProducts([logs, companion('logs_retention_custom', 'logs', true)], 10)
+ const logic = mountLogs()
+
+ expect(logic.values.combinedMonetaryData).toMatchObject({ currentTotal: 90, projectedTotal: 180 })
+ expect(logic.values.totalsIncludingCompanions).toEqual({ currentTotal: 99, projectedTotal: 198 })
+ })
+
+ it('rounds a half-cent header amount the way the card displays it', async () => {
+ const halfCentLogs = { ...logs, current_amount_usd: '2.01', projected_amount_usd_with_limit: '2.01' }
+ await seedProducts(
+ [
+ halfCentLogs,
+ {
+ ...companion('logs_retention_custom', 'logs', true),
+ current_amount_usd: '1.00',
+ projected_amount_usd: '1.00',
+ },
+ ],
+ 50
+ )
+ const logic = mountLogs(halfCentLogs)
+
+ // The header shows $1.01 for $1.005, so the total must be $1.01 + $0.50.
+ expect(logic.values.totalsIncludingCompanions).toEqual({ currentTotal: 1.51, projectedTotal: 1.51 })
+ })
+
+ it('leaves a held companion that can have its own billing limit out of the amounts and the total', async () => {
+ await seedProducts([
+ logs,
+ companion('logs_retention_custom', 'logs', true),
+ { ...companion('logs_limited_extra', 'logs', true), no_billing_limit: undefined },
+ ])
+ const logic = mountLogs()
+
+ expect(logic.values.heldCompanions.map((p) => p.type)).toEqual([
+ 'logs_retention_custom',
+ 'logs_limited_extra',
+ ])
+ expect(logic.values.noLimitCompanionAmounts.map(({ companion }) => companion.type)).toEqual([
+ 'logs_retention_custom',
+ ])
+ expect(logic.values.totalsIncludingCompanions).toEqual({ currentTotal: 110, projectedTotal: 220 })
+ })
+ })
+
describe('unsubscribe survey state', () => {
it('keeps survey responses isolated per product type', async () => {
await seedBilling({})
diff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.ts
index b182cce1b8e1..c28f41e3eaaf 100644
--- a/frontend/src/scenes/billing/billingProductLogic.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.ts
@@ -8,6 +8,7 @@ import React from 'react'
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import type { FeatureFlagKey } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { organizationLogic } from 'scenes/organizationLogic'
@@ -28,6 +29,7 @@ import {
calculateFreeTier,
canHaveBillingLimit,
createGaugeItems,
+ getHeldCompanions,
isAddonVisible,
isProductVariantPrimary,
} from './billing-utils'
@@ -35,12 +37,17 @@ import { getBillingLimitConfig } from './billingLimitConfig'
import type { BillingLimitConfig } from './billingLimitConfig'
import { billingLogic } from './billingLogic'
import type { BillingAlertConfig, SwitchPlanPayload, UnsubscribeError } from './billingLogic'
+import { billingProductRowDisplayName } from './billingProductDisplayName'
import { DATA_PIPELINES_CUTOFF_DATE } from './constants'
import { paymentEntryLogic } from './paymentEntryLogic'
import { BillingGaugeItemKind, BillingGaugeItemType } from './types'
const DEFAULT_BILLING_LIMIT: number = 500
+// Rounds a dollar amount to the cent the same way humanFriendlyCurrency displays it.
+const roundToCents = (amount: number): number =>
+ parseFloat(amount.toLocaleString('en-US', { maximumFractionDigits: 2, useGrouping: false }))
+
type UnsubscribeReason = {
reason: string
question: string
@@ -143,6 +150,7 @@ export interface billingProductLogicValues {
freeTier: number
hasCustomLimitSet: boolean
hedgehogSatisfied: boolean
+ heldCompanions: BillingProductV2Type[]
isAddonProduct: boolean
isBillingLimitInputSubmitting: boolean
isBillingLimitInputValid: boolean
@@ -154,6 +162,11 @@ export interface billingProductLogicValues {
isProductWithVariants: boolean
isProrated: boolean
isSubscribedToAnotherAddon: boolean
+ noLimitCompanionAmounts: {
+ companion: BillingProductV2Type
+ currentAmount: number
+ projectedAmount: number
+ }[]
productVariants: Array<{
displayName: string
key: string
@@ -169,6 +182,10 @@ export interface billingProductLogicValues {
$survey_response: string
$survey_response_2: string[]
}
+ totalsIncludingCompanions: {
+ currentTotal: number
+ projectedTotal: number
+ }
trialCancelReasonQuestions: string
trialLoading: boolean
unsubscribeModalStep: number
@@ -496,6 +513,44 @@ export interface billingProductLogicMeta {
rawCurrentTotal: string
rawProjectedTotal: string
}) => BillingGaugeItemType[]
+ heldCompanions: (
+ billing: BillingType | null,
+ product: BillingProductV2AddonType | BillingProductV2Type
+ ) => BillingProductV2Type[]
+ noLimitCompanionAmounts: (
+ heldCompanions: BillingProductV2Type[],
+ combinedMonetaryData: {
+ billingLimit: number | null
+ currentTotal: number
+ discountPercent: number
+ projectedTotal: number
+ rawCurrentTotal: string
+ rawProjectedTotal: string
+ },
+ featureFlags: FeatureFlagsSet
+ ) => {
+ companion: BillingProductV2Type
+ currentAmount: number
+ projectedAmount: number
+ }[]
+ totalsIncludingCompanions: (
+ combinedMonetaryData: {
+ billingLimit: number | null
+ currentTotal: number
+ discountPercent: number
+ projectedTotal: number
+ rawCurrentTotal: string
+ rawProjectedTotal: string
+ },
+ noLimitCompanionAmounts: {
+ companion: BillingProductV2Type
+ currentAmount: number
+ projectedAmount: number
+ }[]
+ ) => {
+ currentTotal: number
+ projectedTotal: number
+ }
currentAmountTotalActual: (
isProductWithVariants: boolean,
product: BillingProductV2AddonType | BillingProductV2Type,
@@ -1012,15 +1067,6 @@ export const billingProductLogic = kea<billingProductLogicType>([
return null
}
- const displayNameOverrides: Record<string, string> = {
- session_replay: 'Web session replay',
- data_warehouse: 'Synced rows',
- data_warehouse_historical: 'Free historical synced rows',
- logs: 'Logs ingestion (14-day retention)',
- logs_retention_30d: '30-day retention',
- logs_retention_custom: 'Custom retention',
- }
-
const mainProduct = product as BillingProductV2Type
const variants: Array<{
key: string
@@ -1030,7 +1076,7 @@ export const billingProductLogic = kea<billingProductLogicType>([
{
key: mainProduct.type,
product: mainProduct as BillingProductV2Type | BillingProductV2AddonType,
- displayName: displayNameOverrides[mainProduct.type] || mainProduct.name,
+ displayName: billingProductRowDisplayName(mainProduct),
},
]
@@ -1043,7 +1089,7 @@ export const billingProductLogic = kea<billingProductLogicType>([
variants.push({
key: addon.type,
product: addon as BillingProductV2Type | BillingProductV2AddonType,
- displayName: displayNameOverrides[addon.type] || addon.name,
+ displayName: billingProductRowDisplayName(addon),
})
})
@@ -1098,6 +1144,56 @@ export const billingProductLogic = kea<billingProductLogicType>([
].filter(Boolean) as BillingGaugeItemType[]
},
],
+ heldCompanions: [
+ (s, p) => [s.billing, p.product],
+ (
+ billing: BillingType | null,
+ product: BillingProductV2Type | BillingProductV2AddonType
+ ): BillingProductV2Type[] => getHeldCompanions(billing?.products, product.type),
+ ],
+ noLimitCompanionAmounts: [
+ (s) => [s.heldCompanions, s.combinedMonetaryData, s.featureFlags],
+ (
+ heldCompanions: BillingProductV2Type[],
+ monetaryData: { discountPercent: number },
+ featureFlags: FeatureFlagsSet
+ ): { companion: BillingProductV2Type; currentAmount: number; projectedAmount: number }[] => {
+ const discountMultiplier = 1 - monetaryData.discountPercent / 100
+ // A companion that can have its own billing limit gets its own look later.
+ return heldCompanions
+ .filter((companion) => !canHaveBillingLimit(companion))
+ .filter(
+ (companion) => featureFlags[`billing_hide_product_${companion.type}` as FeatureFlagKey] !== true
+ )
+ .map((companion) => ({
+ companion,
+ currentAmount: roundToCents(
+ parseFloat(companion.current_amount_usd || '0') * discountMultiplier
+ ),
+ projectedAmount: roundToCents(
+ parseFloat(companion.projected_amount_usd || '0') * discountMultiplier
+ ),
+ }))
+ },
+ ],
+ totalsIncludingCompanions: [
+ (s) => [s.combinedMonetaryData, s.noLimitCompanionAmounts],
+ (
+ monetaryData: { currentTotal: number; projectedTotal: number },
+ noLimitCompanionAmounts: { currentAmount: number; projectedAmount: number }[]
+ ): { currentTotal: number; projectedTotal: number } =>
+ // Sum the amounts as the card shows them, in cents, so the total matches the figures above it.
+ noLimitCompanionAmounts.reduce(
+ (totals, amounts) => ({
+ currentTotal: totals.currentTotal + amounts.currentAmount,
+ projectedTotal: totals.projectedTotal + amounts.projectedAmount,
+ }),
+ {
+ currentTotal: roundToCents(monetaryData.currentTotal),
+ projectedTotal: roundToCents(monetaryData.projectedTotal),
+ }
+ ),
+ ],
currentAmountTotalActual: [
(s, p) => [s.isProductWithVariants, p.product, s.visibleAddons],
(
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 1374d19268bf..c4e334b6d400 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2418,6 +2418,8 @@ export interface BillingProductV2Type {
legacy_product?: boolean | null
// Billing refuses a customer billing limit for this product and returns no limit for it.
no_billing_limit?: boolean
+ // Set on a companion product: the type of the product whose card it is billed under.
+ companion_of?: string | null
}
export interface BillingProductV2AddonType {