The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(billing): show billing address modal for paid orgs with missing address (#43480)
Kanishk Dudeja83592b1932d1
diff --git a/apps/studio/components/interfaces/App/UpdateBillingAddressModal.tsx b/apps/studio/components/interfaces/App/UpdateBillingAddressModal.tsxnew file mode 100644index 00000000000..929e12b1199--- /dev/null+++ b/apps/studio/components/interfaces/App/UpdateBillingAddressModal.tsx@@ -0,0 +1,172 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useQueryClient } from '@tanstack/react-query'+import { useFlag } from 'common'+import {+ BillingCustomerDataForm,+ type BillingCustomerDataFormValues,+} from 'components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm'+import { TAX_IDS } from 'components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.constants'+import { useBillingCustomerDataForm } from 'components/interfaces/Organization/BillingSettings/BillingCustomerData/useBillingCustomerDataForm'+import { useOrganizationCustomerProfileQuery } from 'data/organizations/organization-customer-profile-query'+import { useOrganizationCustomerProfileUpdateMutation } from 'data/organizations/organization-customer-profile-update-mutation'+import { useOrganizationTaxIdQuery } from 'data/organizations/organization-tax-id-query'+import { useOrganizationTaxIdUpdateMutation } from 'data/organizations/organization-tax-id-update-mutation'+import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'+import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'+import { IS_PLATFORM } from 'lib/constants'+import { useMemo, useState } from 'react'+import { toast } from 'sonner'+import {+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogSection,+ DialogTitle,+ Form_Shadcn_ as Form,+} from 'ui'+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'++export function UpdateBillingAddressModal() {+ const queryClient = useQueryClient()++ const [dismissed, setDismissed] = useState(false)+ const [isSubmitting, setIsSubmitting] = useState(false)++ const showMissingAddressModal = useFlag('enableBillingAddressModal')+ const { data: org } = useSelectedOrganizationQuery()+ const slug = org?.slug++ const { can: canBillingWrite, isSuccess: permissionsLoaded } = useAsyncCheckPermissions(+ PermissionAction.BILLING_WRITE,+ 'stripe.customer'+ )++ const shouldShow =+ IS_PLATFORM &&+ showMissingAddressModal &&+ !!org &&+ org.plan.id !== 'free' &&+ org.organization_missing_address &&+ !org.billing_partner &&+ permissionsLoaded &&+ canBillingWrite++ const {+ data: customerProfile,+ isSuccess: profileLoaded,+ isError: profileError,+ } = useOrganizationCustomerProfileQuery({ slug }, { enabled: shouldShow && !dismissed && !!slug })++ const {+ data: taxId,+ isSuccess: taxIdLoaded,+ isError: taxIdError,+ } = useOrganizationTaxIdQuery({ slug }, { enabled: shouldShow && !dismissed && !!slug })++ const open = shouldShow && !dismissed && !profileError && !taxIdError++ const initialCustomerData = useMemo<Partial<BillingCustomerDataFormValues>>(+ () => ({+ city: customerProfile?.address?.city ?? undefined,+ country: customerProfile?.address?.country,+ line1: customerProfile?.address?.line1,+ line2: customerProfile?.address?.line2 ?? undefined,+ postal_code: customerProfile?.address?.postal_code ?? undefined,+ state: customerProfile?.address?.state ?? undefined,+ billing_name: customerProfile?.billing_name,+ tax_id_type: taxId?.type,+ tax_id_value: taxId?.value,+ tax_id_name: taxId+ ? TAX_IDS.find(+ (option) => option.type === taxId.type && option.countryIso2 === taxId.country+ )?.name || ''+ : '',+ }),+ [customerProfile, taxId]+ )++ const { mutateAsync: updateCustomerProfile } = useOrganizationCustomerProfileUpdateMutation()+ const { mutateAsync: updateTaxId } = useOrganizationTaxIdUpdateMutation()++ const { form, handleSubmit, isDirty } = useBillingCustomerDataForm({+ initialCustomerData,+ onCustomerDataChange: async (data) => {+ if (!slug) return+ setIsSubmitting(true)++ try {+ await updateCustomerProfile({+ slug,+ address: data.address,+ billing_name: data.billing_name,+ })++ await updateTaxId({ slug, taxId: data.tax_id })++ await invalidateOrganizationsQuery(queryClient)++ toast.success('Successfully updated billing address')+ setDismissed(true)+ } catch (error: any) {+ toast.error(`Failed to update billing address: ${error.message}`)+ } finally {+ setIsSubmitting(false)+ }+ },+ })++ return (+ <Dialog+ open={open}+ onOpenChange={(value) => {+ if (!value) setDismissed(true)+ }}+ >+ <DialogContent+ size="medium"+ onInteractOutside={(e) => e.preventDefault()}+ onEscapeKeyDown={(e) => e.preventDefault()}+ >+ <DialogHeader>+ <DialogTitle>Billing address required</DialogTitle>+ <DialogDescription>+ Please provide a billing address for your organization. If you are a registered business+ and have a Tax ID, please add your Tax ID too.+ </DialogDescription>+ </DialogHeader>++ {!profileLoaded || !taxIdLoaded ? (+ <DialogSection>+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ </DialogSection>+ ) : (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(handleSubmit)}>+ <DialogSection className="max-h-[60vh] overflow-y-auto">+ <BillingCustomerDataForm form={form} />+ </DialogSection>+ <DialogFooter>+ <Button+ type="primary"+ htmlType="submit"+ loading={isSubmitting}+ disabled={!isDirty || isSubmitting}+ >+ Save address+ </Button>+ </DialogFooter>+ </form>+ </Form>+ )}+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsxindex b8e795618b2..cef3bddd6d3 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx@@ -109,8 +109,10 @@ export const BillingCustomerData = () => {)setIsSubmitting(false)- } catch (error: any) {- toast.error(`Failed updating billing data: ${error.message}`)+ } catch (error) {+ toast.error(+ `Failed updating billing data: ${error instanceof Error ? error.message : 'Unknown error'}`+ )setIsSubmitting(false)}},diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsxindex 666d5f1a840..6c7bdf13daa 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsx@@ -1,4 +1,4 @@-import { Check, ChevronsUpDown, X } from 'lucide-react'+import { Check, ChevronsUpDown, Info, X } from 'lucide-react'import { useId, useMemo, useState } from 'react'import { UseFormReturn } from 'react-hook-form'import {@@ -17,6 +17,9 @@ import {Popover_Shadcn_ as Popover,PopoverContent_Shadcn_ as PopoverContent,PopoverTrigger_Shadcn_ as PopoverTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,} from 'ui'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { z } from 'zod'@@ -246,7 +249,24 @@ export const BillingCustomerDataForm = ({name="tax_id_name"control={form.control}render={() => (- <FormItemLayout hideMessage layout="vertical" label="Tax ID">+ <FormItemLayout+ hideMessage+ layout="vertical"+ label="Business Tax ID"+ afterLabel={+ <Tooltip>+ <TooltipTrigger asChild>+ <Info size={14} className="text-foreground-lighter cursor-pointer" />+ </TooltipTrigger>+ <TooltipContent side="right" className="max-w-xs text-left">+ If you are an individual, no need to add a Tax ID. If you are a business below+ your country's income threshold and don't have a Tax ID, you can leave this+ blank. Taxes will be added to your invoice according to your country's tax laws+ in the near future.+ </TooltipContent>+ </Tooltip>+ }+ ><Popover open={showTaxIDsPopover} onOpenChange={setShowTaxIDsPopover}><PopoverTrigger asChild><FormControl>diff --git a/apps/studio/components/interfaces/Organization/restriction.constants.tsx b/apps/studio/components/interfaces/Organization/restriction.constants.tsxindex 39decb10a6d..90026eae695 100644--- a/apps/studio/components/interfaces/Organization/restriction.constants.tsx+++ b/apps/studio/components/interfaces/Organization/restriction.constants.tsx@@ -48,13 +48,4 @@ export const RESTRICTION_MESSAGES = {</>),},- MISSING_BILLING_INFO: {- title: 'Missing billing information',- description: (slug: string): ReactNode => (- <>- Please <InlineLink href={`/org/${slug}/billing#address`}>add a billing address</InlineLink>{' '}- to avoid restrictions. If you are a registered business, please add a tax ID too- </>- ),- },}diff --git a/apps/studio/hooks/misc/useOrganizationRestrictions.ts b/apps/studio/hooks/misc/useOrganizationRestrictions.tsindex 66435f04981..510cd12b9ac 100644--- a/apps/studio/hooks/misc/useOrganizationRestrictions.ts+++ b/apps/studio/hooks/misc/useOrganizationRestrictions.ts@@ -43,14 +43,6 @@ export function useOrganizationRestrictions() {(invoice) => invoice.organization_id === org?.id)- if (org && org.organization_missing_address && !org.billing_partner) {- warnings.push({- variant: 'danger',- title: RESTRICTION_MESSAGES.MISSING_BILLING_INFO.title,- description: RESTRICTION_MESSAGES.MISSING_BILLING_INFO.description(org.slug),- })- }-if (thisOrgHasOverdueInvoices?.length) {warnings.push({variant: 'danger',diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsxindex cc728710970..a6f6f4aaf6f 100644--- a/apps/studio/pages/_app.tsx+++ b/apps/studio/pages/_app.tsx@@ -35,6 +35,7 @@ import { StudioCommandMenu } from 'components/interfaces/App/CommandMenu'import { StudioCommandProvider as CommandProvider } from 'components/interfaces/App/CommandMenu/StudioCommandProvider'import { FeaturePreviewContextProvider } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { FeaturePreviewModal } from 'components/interfaces/App/FeaturePreview/FeaturePreviewModal'+import { UpdateBillingAddressModal } from 'components/interfaces/App/UpdateBillingAddressModal'import { MonacoThemeProvider } from 'components/interfaces/App/MonacoThemeProvider'import { RouteValidationWrapper } from 'components/interfaces/App/RouteValidationWrapper'import { MainScrollContainerProvider } from 'components/layouts/MainScrollContainerContext'@@ -182,6 +183,7 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {</MainScrollContainerProvider><StudioCommandMenu /><FeaturePreviewModal />+ <UpdateBillingAddressModal /></FeaturePreviewContextProvider><SonnerToaster position="top-right" /><MonacoThemeProvider />diff --git a/apps/studio/tests/components/Billing/UpdateBillingAddressModal.test.tsx b/apps/studio/tests/components/Billing/UpdateBillingAddressModal.test.tsxnew file mode 100644index 00000000000..0099dd5b288--- /dev/null+++ b/apps/studio/tests/components/Billing/UpdateBillingAddressModal.test.tsx@@ -0,0 +1,191 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { UpdateBillingAddressModal } from 'components/interfaces/App/UpdateBillingAddressModal'+import { createMockOrganization, render } from 'tests/helpers'+import { beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('lib/constants', async (importOriginal) => {+ const original = (await importOriginal()) as any+ return { ...original, IS_PLATFORM: true }+})++const mockFlag = vi.fn(() => true)+vi.mock('common', async (importOriginal) => {+ const original = (await importOriginal()) as any+ return {+ ...original,+ useFlag: (_name: string) => mockFlag(),+ useParams: () => ({ slug: 'test-org' }),+ }+})++const mockOrg = vi.fn(() =>+ createMockOrganization({+ slug: 'test-org',+ organization_missing_address: true,+ billing_partner: null,+ })+)+vi.mock('hooks/misc/useSelectedOrganization', () => ({+ useSelectedOrganizationQuery: () => ({ data: mockOrg() }),+}))++const mockCanWrite = vi.fn(() => true)+const mockPermissionsLoaded = vi.fn(() => true)+vi.mock('hooks/misc/useCheckPermissions', () => ({+ useAsyncCheckPermissions: () => ({+ can: mockCanWrite(),+ isSuccess: mockPermissionsLoaded(),+ }),+}))++const mockCustomerProfile = vi.fn(() => ({+ address: { line1: '', line2: '', city: '', state: '', postal_code: '', country: '' },+ billing_name: '',+}))+const mockProfileLoaded = vi.fn(() => true)+const mockProfileError = vi.fn(() => false)+vi.mock('data/organizations/organization-customer-profile-query', () => ({+ useOrganizationCustomerProfileQuery: () => ({+ data: mockCustomerProfile(),+ isSuccess: mockProfileLoaded(),+ isError: mockProfileError(),+ }),+}))++const mockTaxId = vi.fn(() => null)+const mockTaxIdLoaded = vi.fn(() => true)+const mockTaxIdError = vi.fn(() => false)+vi.mock('data/organizations/organization-tax-id-query', () => ({+ useOrganizationTaxIdQuery: () => ({+ data: mockTaxId(),+ isSuccess: mockTaxIdLoaded(),+ isError: mockTaxIdError(),+ }),+}))++const mockUpdateCustomerProfile = vi.fn(() => Promise.resolve())+vi.mock('data/organizations/organization-customer-profile-update-mutation', () => ({+ useOrganizationCustomerProfileUpdateMutation: () => ({+ mutateAsync: mockUpdateCustomerProfile,+ }),+}))++const mockUpdateTaxId = vi.fn(() => Promise.resolve())+vi.mock('data/organizations/organization-tax-id-update-mutation', () => ({+ useOrganizationTaxIdUpdateMutation: () => ({+ mutateAsync: mockUpdateTaxId,+ }),+}))++vi.mock('data/organizations/organizations-query', () => ({+ invalidateOrganizationsQuery: vi.fn(() => Promise.resolve()),+}))++describe('UpdateBillingAddressModal', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFlag.mockReturnValue(true)+ mockOrg.mockReturnValue(+ createMockOrganization({+ slug: 'test-org',+ organization_missing_address: true,+ billing_partner: null,+ plan: { id: 'pro', name: 'Pro' },+ })+ )+ mockCanWrite.mockReturnValue(true)+ mockPermissionsLoaded.mockReturnValue(true)+ mockProfileLoaded.mockReturnValue(true)+ mockTaxIdLoaded.mockReturnValue(true)+ mockCustomerProfile.mockReturnValue({+ address: { line1: '', line2: '', city: '', state: '', postal_code: '', country: '' },+ billing_name: '',+ })+ mockTaxId.mockReturnValue(null)+ mockProfileError.mockReturnValue(false)+ mockTaxIdError.mockReturnValue(false)+ })++ it('renders when all conditions are met', async () => {+ render(<UpdateBillingAddressModal />)+ expect(await screen.findByText('Billing address required')).toBeInTheDocument()+ })++ it('does not render when feature flag is off', () => {+ mockFlag.mockReturnValue(false)+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render when org has no missing address', () => {+ mockOrg.mockReturnValue(createMockOrganization({ organization_missing_address: false }))+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render for free orgs', () => {+ mockOrg.mockReturnValue(+ createMockOrganization({+ organization_missing_address: true,+ plan: { id: 'free', name: 'Free' },+ })+ )+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render for partner-managed orgs', () => {+ mockOrg.mockReturnValue(+ createMockOrganization({+ organization_missing_address: true,+ billing_partner: 'vercel_marketplace',+ })+ )+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render when user lacks billing write permission', () => {+ mockCanWrite.mockReturnValue(false)+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render when no org is selected', () => {+ mockOrg.mockReturnValue(undefined as any)+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render when customer profile query errors', () => {+ mockProfileError.mockReturnValue(true)+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('does not render when tax id query errors', () => {+ mockTaxIdError.mockReturnValue(true)+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })++ it('shows loading shimmer while customer data loads', () => {+ mockProfileLoaded.mockReturnValue(false)+ render(<UpdateBillingAddressModal />)+ expect(screen.queryByText('Save address')).not.toBeInTheDocument()+ })++ it('dismisses on close button click', async () => {+ render(<UpdateBillingAddressModal />)+ expect(await screen.findByText('Billing address required')).toBeInTheDocument()++ // Click the X (close) button in DialogContent+ const closeButton = screen.getByRole('button', { name: /close/i })+ await userEvent.click(closeButton)++ await waitFor(() => {+ expect(screen.queryByText('Billing address required')).not.toBeInTheDocument()+ })+ })+})