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.

fix(billing): send externally billed orgs to their provider's invoices (#107953)

Matt Brooker9dd9623b1f27
diff --git a/frontend/src/scenes/billing/CreditCTAHero.tsx b/frontend/src/scenes/billing/CreditCTAHero.tsx
index 66c3f022dddf..dc866ae0fe83 100644
--- a/frontend/src/scenes/billing/CreditCTAHero.tsx
+++ b/frontend/src/scenes/billing/CreditCTAHero.tsx
@@ -15,14 +15,19 @@ export const DEFAULT_ESTIMATED_MONTHLY_CREDIT_AMOUNT_USD = 500
export const CreditCTAHero = (): JSX.Element | null => {
const {
+ billing,
creditOverview,
isPurchaseCreditsModalOpen,
isCreditCTAHeroDismissed,
computedDiscount,
showCreditCTAHero,
+ isExternallyBilled,
} = useValues(billingLogic)
const { showPurchaseCreditsModal, toggleCreditCTAHeroDismissed } = useActions(billingLogic)
const { estimatedMonthlyCreditAmountUsd } = useValues(billingLogic)
+ const creditInvoiceUrl = isExternallyBilled
+ ? billing?.external_billing_provider_invoices_url
+ : creditOverview.invoice_url
if (!showCreditCTAHero) {
return null
@@ -129,15 +134,13 @@ export const CreditCTAHero = (): JSX.Element | null => {
</div>
<div className="flex flex-col justify-center items-end w-30">
<HedgehogBurningMoney className="w-full h-auto" />
- {creditOverview.status === 'pending' && creditOverview.invoice_url && (
+ {creditOverview.status === 'pending' && creditInvoiceUrl && (
<LemonButton
type="primary"
- onClick={() =>
- creditOverview.invoice_url && window.open(creditOverview.invoice_url, '_blank')
- }
+ onClick={() => window.open(creditInvoiceUrl, '_blank')}
className="w-30 mt-4"
>
- View invoice
+ {isExternallyBilled ? 'View invoices' : 'View invoice'}
</LemonButton>
)}
{creditOverview.status === 'none' && (
diff --git a/frontend/src/scenes/billing/StripePortalButton.test.tsx b/frontend/src/scenes/billing/StripePortalButton.test.tsx
new file mode 100644
index 000000000000..f7003c4b6222
--- /dev/null
+++ b/frontend/src/scenes/billing/StripePortalButton.test.tsx
@@ -0,0 +1,71 @@
+/* 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 } from '@testing-library/react'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { billingJson } from '~/mocks/fixtures/_billing'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { BillingProvider, BillingType } from '~/types'
+
+import { billingLogic } from './billingLogic'
+import { StripePortalButton } from './StripePortalButton'
+
+const EXTERNAL_INVOICES_URL = 'https://vercel.com/example-team/~/integrations/posthog/icfg_example/invoices'
+
+describe('StripePortalButton', () => {
+ const renderForBilling = async (billing: Partial<BillingType>): Promise<HTMLElement> => {
+ useMocks({ get: { '/api/billing': [200, { ...billingJson, ...billing }] } })
+ billingLogic.mount()
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ return render(
+ <Provider>
+ <StripePortalButton />
+ </Provider>
+ ).container
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ {
+ name: 'the Stripe portal when PostHog bills the organization',
+ billing: { billing_provider: BillingProvider.PostHog },
+ expectedLabel: 'Manage card details and invoices',
+ expectedHref: billingJson.stripe_portal_url,
+ },
+ {
+ name: 'the external provider invoices page',
+ billing: { external_billing_provider_invoices_url: EXTERNAL_INVOICES_URL },
+ expectedLabel: 'View invoices in Vercel',
+ expectedHref: EXTERNAL_INVOICES_URL,
+ },
+ {
+ name: 'the external provider invoices page when billing has no customer id',
+ billing: { external_billing_provider_invoices_url: EXTERNAL_INVOICES_URL, customer_id: '' },
+ expectedLabel: 'View invoices in Vercel',
+ expectedHref: EXTERNAL_INVOICES_URL,
+ },
+ ])('links to $name', async ({ billing, expectedLabel, expectedHref }) => {
+ await renderForBilling(billing)
+
+ expect(screen.getByText(expectedLabel).closest('a')).toHaveAttribute('href', expectedHref)
+ })
+
+ it('renders nothing when an external provider has no invoices page', async () => {
+ const container = await renderForBilling({ billing_provider: BillingProvider.Vercel })
+
+ expect(container).toBeEmptyDOMElement()
+ })
+})
diff --git a/frontend/src/scenes/billing/StripePortalButton.tsx b/frontend/src/scenes/billing/StripePortalButton.tsx
index 57aa3bdcc328..cea99e630e12 100644
--- a/frontend/src/scenes/billing/StripePortalButton.tsx
+++ b/frontend/src/scenes/billing/StripePortalButton.tsx
@@ -5,13 +5,13 @@ import { LemonButton } from '@posthog/lemon-ui'
import { billingLogic } from './billingLogic'
export const StripePortalButton = (): JSX.Element | null => {
- const { billing } = useValues(billingLogic)
+ const { billing, isExternallyBilled } = useValues(billingLogic)
- if (!billing?.customer_id) {
+ if (!billing || (!isExternallyBilled && !billing.customer_id)) {
return null
}
- const billingUrl = billing.external_billing_provider_invoices_url || billing.stripe_portal_url
+ const billingUrl = isExternallyBilled ? billing.external_billing_provider_invoices_url : billing.stripe_portal_url
if (!billingUrl) {
return null
@@ -28,7 +28,11 @@ export const StripePortalButton = (): JSX.Element | null => {
center
data-attr="manage-billing"
>
- {billing.has_active_subscription ? 'Manage card details and invoices' : 'View past invoices'}
+ {isExternallyBilled
+ ? 'View invoices in Vercel'
+ : billing.has_active_subscription
+ ? 'Manage card details and invoices'
+ : 'View past invoices'}
</LemonButton>
</div>
)
diff --git a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
index 35794b5ed2f1..3150f757547f 100644
--- a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
+++ b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
@@ -57,12 +57,15 @@ export const UnsubscribeSurveyModal = ({
triggerMoreHedgehogs,
} = useActions(billingProductLogic({ product }))
const { deactivateProduct, resetUnsubscribeError } = useActions(billingLogic)
- const { unsubscribeError, billingLoading, billing } = useValues(billingLogic)
+ const { unsubscribeError, billingLoading, billing, isExternallyBilled } = useValues(billingLogic)
const { openSupportForm } = useActions(supportLogic)
const [randomizedReasons] = useState(() =>
inStorybook() || inStorybookTestRunner() ? UNSUBSCRIBE_REASONS : randomizeReasons(UNSUBSCRIBE_REASONS)
)
+ const invoicesUrl = isExternallyBilled
+ ? billing?.external_billing_provider_invoices_url
+ : billing?.stripe_portal_url
const textAreaNotEmpty = surveyResponse[SurveyEventProperties.SURVEY_RESPONSE]?.length > 0
const isOnDiscountedPrice = isAddonProduct && (product as BillingProductV2AddonType).default_unit_amount_usd != null
@@ -201,9 +204,11 @@ export const UnsubscribeSurveyModal = ({
We're sorry to see you go! Please note, you'll lose access to platform features and
usage limits will apply immediately. And if you have any outstanding invoices, they will
be billed immediately.{' '}
- <Link to={billing?.stripe_portal_url} target="_blank">
- View invoices
- </Link>
+ {invoicesUrl && (
+ <Link to={invoicesUrl} target="_blank">
+ View invoices
+ </Link>
+ )}
</p>
)}
diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.ts
index 157822ccf425..1553f2dbf864 100644
--- a/frontend/src/scenes/billing/billingLogic.test.ts
+++ b/frontend/src/scenes/billing/billingLogic.test.ts
@@ -1,3 +1,4 @@
+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
import { router } from 'kea-router'
@@ -6,7 +7,7 @@ import posthog from 'posthog-js'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { billingLogic } from 'scenes/billing/billingLogic'
+import { BillingAPIErrorCodes, billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
@@ -16,7 +17,7 @@ import preflightJson from '~/mocks/fixtures/_preflight.json'
import { useMocks } from '~/mocks/jest'
import { ProductKey } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { BillingProductV2Type, BillingType } from '~/types'
+import { BillingProductV2Type, BillingProvider, BillingType } from '~/types'
const creditOverviewResponse = {
eligible: false,
@@ -29,6 +30,10 @@ const creditOverviewResponse = {
credit_brackets: [],
}
+const EXTERNAL_INVOICES_URL = 'https://vercel.com/example-team/~/integrations/posthog/icfg_example/invoices'
+const HOSTED_INVOICE_URL = 'https://invoice.stripe.com/i/acct_example/test_example'
+const UNSUBSCRIBE_ERROR_DETAIL = 'Pay your open invoices first.'
+
const productWithUsage = (
percentageUsage: number,
overrides: Partial<BillingProductV2Type> = {}
@@ -314,4 +319,239 @@ describe('billingLogic', () => {
expect(billingLogic.values.canOnlyViewUsageAndSpend).toBe(expected.canOnlyViewUsageAndSpend)
expect(billingLogic.values.billingEntryUrl).toBe(expected.billingEntryUrl)
})
+
+ const loadOpenInvoiceBanner = async (
+ billing: Partial<BillingType>,
+ openInvoices: { count: number; link: string | null },
+ billingLoadsFirst: boolean
+ ): Promise<number> => {
+ // Reading a lazy value starts its load on a timer that can outlive the test that read it.
+ // Let timers from earlier tests fire before this logic mounts, so they cannot add to the count.
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ billingState = { ...billingState, ...billing }
+ let billingRequests = 0
+ let releaseBilling = (): void => {}
+ const billingReleased = new Promise<void>((resolve) => {
+ releaseBilling = resolve
+ })
+ useMocks({
+ get: {
+ '/api/billing': async () => {
+ billingRequests += 1
+ // Only the first request waits, so a duplicate request answers and shows up in the count.
+ if (billingRequests === 1) {
+ await billingReleased
+ }
+ return [200, billingState]
+ },
+ '/api/billing/get_invoices': [200, openInvoices],
+ },
+ })
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+
+ if (billingLoadsFirst) {
+ releaseBilling()
+ await expectLogic(billingLogic, () => {
+ expect(billingLogic.values.billing).toBeNull()
+ }).toDispatchActions(['loadBillingSuccess'])
+ await expectLogic(billingLogic, () => {
+ expect(billingLogic.values.billingError).toBeNull()
+ }).toDispatchActions(['loadInvoicesSuccess'])
+ } else {
+ await expectLogic(billingLogic, () => {
+ expect(billingLogic.values.billing).toBeNull()
+ expect(billingLogic.values.billingError).toBeNull()
+ }).toDispatchActions(['loadInvoicesSuccess'])
+ releaseBilling()
+ }
+ await expectLogic(billingLogic).toFinishAllListeners()
+
+ return billingRequests
+ }
+
+ const failDeactivation = async (
+ billing: Partial<BillingType>,
+ code: BillingAPIErrorCodes,
+ invoiceLink: string | null
+ ): Promise<void> => {
+ billingState = { ...billingState, ...billing }
+ useMocks({
+ post: {
+ '/api/billing/deactivate': [400, { code, detail: UNSUBSCRIBE_ERROR_DETAIL, link: invoiceLink }],
+ },
+ })
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.deactivateProduct(ProductKey.PRODUCT_ANALYTICS)
+ }).toFinishAllListeners()
+ }
+
+ it.each<{
+ name: string
+ billingProvider?: BillingProvider
+ externalInvoicesUrl?: string
+ openInvoices: { count: number; link: string | null }
+ billingLoadsFirst: boolean
+ expectedLink: string | undefined
+ expectedLabel: string
+ }>([
+ {
+ name: 'the hosted invoice when one invoice is open',
+ openInvoices: { count: 1, link: HOSTED_INVOICE_URL },
+ billingLoadsFirst: true,
+ expectedLink: HOSTED_INVOICE_URL,
+ expectedLabel: 'View invoice',
+ },
+ {
+ name: 'the Stripe portal when several invoices are open',
+ openInvoices: { count: 2, link: null },
+ billingLoadsFirst: true,
+ expectedLink: billingJson.stripe_portal_url,
+ expectedLabel: 'View invoices',
+ },
+ {
+ name: 'the external provider instead of the hosted invoice',
+ externalInvoicesUrl: EXTERNAL_INVOICES_URL,
+ openInvoices: { count: 1, link: HOSTED_INVOICE_URL },
+ billingLoadsFirst: true,
+ expectedLink: EXTERNAL_INVOICES_URL,
+ expectedLabel: 'View invoices',
+ },
+ {
+ name: 'the external provider instead of the Stripe portal',
+ externalInvoicesUrl: EXTERNAL_INVOICES_URL,
+ openInvoices: { count: 2, link: null },
+ billingLoadsFirst: true,
+ expectedLink: EXTERNAL_INVOICES_URL,
+ expectedLabel: 'View invoices',
+ },
+ {
+ name: 'the external provider when invoices finish while billing is still loading',
+ externalInvoicesUrl: EXTERNAL_INVOICES_URL,
+ openInvoices: { count: 1, link: HOSTED_INVOICE_URL },
+ billingLoadsFirst: false,
+ expectedLink: EXTERNAL_INVOICES_URL,
+ expectedLabel: 'View invoices',
+ },
+ {
+ name: 'the hosted invoice when PostHog bills the organization',
+ billingProvider: BillingProvider.PostHog,
+ openInvoices: { count: 1, link: HOSTED_INVOICE_URL },
+ billingLoadsFirst: true,
+ expectedLink: HOSTED_INVOICE_URL,
+ expectedLabel: 'View invoice',
+ },
+ ])(
+ 'links the open invoice banner to $name',
+ async ({
+ billingProvider,
+ externalInvoicesUrl,
+ openInvoices,
+ billingLoadsFirst,
+ expectedLink,
+ expectedLabel,
+ }) => {
+ const billingRequests = await loadOpenInvoiceBanner(
+ { billing_provider: billingProvider, external_billing_provider_invoices_url: externalInvoicesUrl },
+ openInvoices,
+ billingLoadsFirst
+ )
+
+ expect(billingRequests).toBe(1)
+ expect(billingLogic.values.billingError).toEqual({
+ status: 'warning',
+ message: expect.stringContaining(`You have ${openInvoices.count} open invoice`),
+ action: { to: expectedLink, children: expectedLabel, targetBlank: true },
+ })
+ }
+ )
+
+ it.each([
+ { name: 'one open invoice', openInvoices: { count: 1, link: HOSTED_INVOICE_URL }, billingLoadsFirst: true },
+ { name: 'several open invoices', openInvoices: { count: 2, link: null }, billingLoadsFirst: true },
+ {
+ name: 'invoices that finish while billing is still loading',
+ openInvoices: { count: 1, link: HOSTED_INVOICE_URL },
+ billingLoadsFirst: false,
+ },
+ ])(
+ 'hides the open invoice banner when an external provider has no invoices page ($name)',
+ async ({ openInvoices, billingLoadsFirst }) => {
+ await loadOpenInvoiceBanner({ billing_provider: BillingProvider.Vercel }, openInvoices, billingLoadsFirst)
+
+ expect(billingLogic.values.billingError).toBeNull()
+ }
+ )
+
+ it.each<{
+ name: string
+ code: BillingAPIErrorCodes
+ externalInvoicesUrl?: string
+ invoiceLink: string | null
+ expectedLink: string | undefined
+ expectedLabel: string
+ }>([
+ {
+ name: 'open invoices to the Stripe portal',
+ code: BillingAPIErrorCodes.OPEN_INVOICES_ERROR,
+ invoiceLink: null,
+ expectedLink: billingJson.stripe_portal_url,
+ expectedLabel: 'View invoices',
+ },
+ {
+ name: 'an unpaid invoice to its hosted invoice',
+ code: BillingAPIErrorCodes.COULD_NOT_PAY_INVOICES_ERROR,
+ invoiceLink: HOSTED_INVOICE_URL,
+ expectedLink: HOSTED_INVOICE_URL,
+ expectedLabel: 'View invoice',
+ },
+ {
+ name: 'open invoices to the external provider',
+ code: BillingAPIErrorCodes.OPEN_INVOICES_ERROR,
+ externalInvoicesUrl: EXTERNAL_INVOICES_URL,
+ invoiceLink: null,
+ expectedLink: EXTERNAL_INVOICES_URL,
+ expectedLabel: 'View invoices',
+ },
+ {
+ name: 'an unpaid invoice to the external provider',
+ code: BillingAPIErrorCodes.COULD_NOT_PAY_INVOICES_ERROR,
+ externalInvoicesUrl: EXTERNAL_INVOICES_URL,
+ invoiceLink: HOSTED_INVOICE_URL,
+ expectedLink: EXTERNAL_INVOICES_URL,
+ expectedLabel: 'View invoices',
+ },
+ ])(
+ 'links the unsubscribe error for $name',
+ async ({ code, externalInvoicesUrl, invoiceLink, expectedLink, expectedLabel }) => {
+ await failDeactivation({ external_billing_provider_invoices_url: externalInvoicesUrl }, code, invoiceLink)
+
+ expect(billingLogic.values.unsubscribeError?.link.props).toMatchObject({
+ to: expectedLink,
+ children: expectedLabel,
+ })
+ }
+ )
+
+ it.each([
+ { name: 'open invoices', code: BillingAPIErrorCodes.OPEN_INVOICES_ERROR, invoiceLink: null },
+ {
+ name: 'an unpaid invoice',
+ code: BillingAPIErrorCodes.COULD_NOT_PAY_INVOICES_ERROR,
+ invoiceLink: HOSTED_INVOICE_URL,
+ },
+ ])(
+ 'keeps the unsubscribe error for $name without a link when an external provider has no invoices page',
+ async ({ code, invoiceLink }) => {
+ await failDeactivation({ billing_provider: BillingProvider.Vercel }, code, invoiceLink)
+
+ expect(billingLogic.values.unsubscribeError).toEqual({ detail: UNSUBSCRIBE_ERROR_DETAIL })
+ }
+ )
})
diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsx
index 1eaa6e5ed6f4..01bbc4c1af4e 100644
--- a/frontend/src/scenes/billing/billingLogic.tsx
+++ b/frontend/src/scenes/billing/billingLogic.tsx
@@ -28,6 +28,7 @@ import {
BillingPlanType,
BillingProductV2AddonType,
BillingProductV2Type,
+ BillingProvider,
BillingType,
StartupProgramLabel,
} from '~/types'
@@ -94,6 +95,11 @@ export interface BillingError {
action: LemonButtonPropsBase
}
+export interface OpenInvoices {
+ count: number
+ link: string | null
+}
+
export type SwitchPlanPayload = {
from_product_key: string
from_plan_key: string
@@ -208,7 +214,6 @@ export interface billingLogicValues {
billingAlert: BillingAlertConfig | null
billingEntryUrl: string | null
billingError: BillingError | null
- billingErrorLoading: boolean
billingLoading: boolean
billingPeriodUTC: BillingPeriod
billingPlan: BillingPlan | null
@@ -262,6 +267,7 @@ export interface billingLogicValues {
isCreditCTAHeroDismissed: boolean
isCreditFormSubmitting: boolean
isCreditFormValid: boolean
+ isExternallyBilled: boolean
isManagedAccount: boolean
isOnboarding: boolean
isProductAtOrOverUsageLimit: (productKey: ProductKey) => boolean
@@ -269,6 +275,8 @@ export interface billingLogicValues {
isUnlicensedDebug: boolean
minimumBillingAccessLevel: OrganizationMembershipLevel
minimumUsageSpendReadAccessLevel: OrganizationMembershipLevel
+ openInvoices: OpenInvoices | null
+ openInvoicesLoading: boolean
platformAddons: BillingProductV2AddonType[]
productSpecificAlert: BillingAlertConfig | null
products: BillingProductV2Type[]
@@ -383,26 +391,10 @@ export interface billingLogicActions {
errorObject?: any
}
loadInvoicesSuccess: (
- billingError: {
- action: {
- children: string
- targetBlank: boolean
- to: any
- }
- message: string
- status: 'warning'
- } | null,
+ openInvoices: OpenInvoices | null,
payload?: any
) => {
- billingError: {
- action: {
- children: string
- targetBlank: boolean
- to: any
- }
- message: string
- status: 'warning'
- } | null
+ openInvoices: OpenInvoices | null
payload?: any
}
loadProducts: () => any
@@ -667,6 +659,12 @@ export interface billingLogicMeta {
showCreditCTAHero: boolean
) => boolean
isManagedAccount: (billing: BillingType | null) => boolean
+ isExternallyBilled: (billing: BillingType | null) => boolean
+ billingError: (
+ openInvoices: OpenInvoices | null,
+ billing: BillingType | null,
+ isExternallyBilled: boolean
+ ) => BillingError | null
accountOwner: (billing: BillingType | null) => {
email?: string
name?: string
@@ -909,26 +907,34 @@ export const billingLogic = kea<billingLogicType>([
} catch (error: any) {
if (error.code) {
if (error.code === BillingAPIErrorCodes.OPEN_INVOICES_ERROR) {
+ const invoicesUrl = values.isExternallyBilled
+ ? values.billing?.external_billing_provider_invoices_url
+ : values.billing?.stripe_portal_url
actions.setUnsubscribeError({
detail: error.detail,
- link: (
- <Link to={values.billing?.stripe_portal_url} target="_blank">
+ link: invoicesUrl ? (
+ <Link to={invoicesUrl} target="_blank">
View invoices
</Link>
- ),
+ ) : undefined,
} as UnsubscribeError)
} else if (error.code === BillingAPIErrorCodes.NO_ACTIVE_PAYMENT_METHOD_ERROR) {
actions.setUnsubscribeError({
detail: error.detail,
} as UnsubscribeError)
} else if (error.code === BillingAPIErrorCodes.COULD_NOT_PAY_INVOICES_ERROR) {
+ const invoicesUrl = values.isExternallyBilled
+ ? values.billing?.external_billing_provider_invoices_url
+ : error.link || values.billing?.stripe_portal_url
actions.setUnsubscribeError({
detail: error.detail,
- link: (
- <Link to={error.link || values.billing?.stripe_portal_url} target="_blank">
- {error.link ? 'View invoice' : 'View invoices'}
+ link: invoicesUrl ? (
+ <Link to={invoicesUrl} target="_blank">
+ {error.link && !values.isExternallyBilled
+ ? 'View invoice'
+ : 'View invoices'}
</Link>
- ),
+ ) : undefined,
} as UnsubscribeError)
}
} else {
@@ -973,35 +979,15 @@ export const billingLogic = kea<billingLogicType>([
},
},
],
- billingError: [
- null as BillingError | null,
+ openInvoices: [
+ null as OpenInvoices | null,
{
- loadInvoices: async () => {
- // First check to see if there are open invoices
+ loadInvoices: async (): Promise<OpenInvoices | null> => {
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingGetInvoicesRetrieve() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
const res = await api.getResponse('api/billing/get_invoices?status=open')
const jsonRes = await getJSONOrNull(res)
- const numOpenInvoices = jsonRes['count']
- if (numOpenInvoices > 0) {
- const viewInvoicesButton = {
- to:
- numOpenInvoices == 1 && jsonRes['link']
- ? jsonRes['link']
- : values.billing?.stripe_portal_url,
- children: `View invoice${numOpenInvoices > 1 ? 's' : ''}`,
- targetBlank: true,
- }
- return {
- status: 'warning',
- message: `You have ${numOpenInvoices} open invoice${
- numOpenInvoices > 1 ? 's' : ''
- }. Please pay ${
- numOpenInvoices > 1 ? 'them' : 'it'
- } before adding items to your subscription.`,
- action: viewInvoicesButton,
- }
- }
+ return { count: jsonRes['count'], link: jsonRes['link'] }
} catch (error: any) {
console.error(error)
}
@@ -1256,6 +1242,45 @@ export const billingLogic = kea<billingLogicType>([
return !!(billing?.account_owner?.name || billing?.account_owner?.email)
},
],
+ isExternallyBilled: [
+ (s) => [s.billing],
+ (billing: BillingType | null): boolean =>
+ (!!billing?.billing_provider && billing.billing_provider !== BillingProvider.PostHog) ||
+ !!billing?.external_billing_provider_invoices_url,
+ ],
+ billingError: [
+ (s) => [s.openInvoices, s.billing, s.isExternallyBilled],
+ (
+ openInvoices: OpenInvoices | null,
+ billing: BillingType | null,
+ isExternallyBilled: boolean
+ ): BillingError | null => {
+ if (!billing || !openInvoices?.count) {
+ return null
+ }
+ const numOpenInvoices = openInvoices.count
+ const stripeInvoicesUrl =
+ numOpenInvoices == 1 && openInvoices.link ? openInvoices.link : billing.stripe_portal_url
+ const invoicesUrl = isExternallyBilled
+ ? billing.external_billing_provider_invoices_url
+ : stripeInvoicesUrl
+ if (!invoicesUrl) {
+ return null
+ }
+ const viewInvoicesButton = {
+ to: invoicesUrl,
+ children: `View invoice${isExternallyBilled || numOpenInvoices > 1 ? 's' : ''}`,
+ targetBlank: true,
+ }
+ return {
+ status: 'warning',
+ message: `You have ${numOpenInvoices} open invoice${
+ numOpenInvoices > 1 ? 's' : ''
+ }. Please pay ${numOpenInvoices > 1 ? 'them' : 'it'} before adding items to your subscription.`,
+ action: viewInvoicesButton,
+ }
+ },
+ ],
accountOwner: [
(s) => [s.billing],
(billing: BillingType): { name?: string; email?: string } | null => billing?.account_owner || null,
@@ -1332,6 +1357,9 @@ export const billingLogic = kea<billingLogicType>([
actions.loadCreditOverview()
actions.reportCreditsFormSubmitted(+creditInput)
+ const billingUrl = values.isExternallyBilled
+ ? values.billing?.external_billing_provider_invoices_url
+ : values.billing?.stripe_portal_url
LemonDialog.open({
title: 'Your credit purchase has been submitted',
width: 536,
@@ -1347,14 +1375,33 @@ export const billingLogic = kea<billingLogicType>([
invoice is paid you will be charged for usage as normal.
</p>
</>
+ ) : values.isExternallyBilled ? (
+ <p>
+ Your billing provider will collect the payment, and the credits will be applied to your
+ account once it does.
+ {billingUrl ? (
+ <>
+ {' '}
+ Please make sure your{' '}
+ <Link to={billingUrl} target="_blank">
+ payment method with your provider
+ </Link>{' '}
+ is up to date.
+ </>
+ ) : null}
+ </p>
) : (
<>
<p>
Your card will be charged soon and the credits will be applied to your account.
Please make sure your{' '}
- <Link to={values.billing?.stripe_portal_url} target="_blank">
- card on file
- </Link>{' '}
+ {billingUrl ? (
+ <Link to={billingUrl} target="_blank">
+ card on file
+ </Link>
+ ) : (
+ 'card on file'
+ )}{' '}
is up to date. You will receive an email when the credits are applied.
</p>
</>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 8240f7fd3db7..429155cfb034 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2435,6 +2435,7 @@ export interface BillingProductV2AddonType {
legacy_product?: boolean | null
}
export enum BillingProvider {
+ PostHog = 'posthog',
Vercel = 'vercel',
}
export interface BillingType {