Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: billing address, name and tax id for org creation/upgrade (#34922)

Saxon Fletcher3aadc009e6a9
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
deleted file mode 100644
index 0275aaae5f7..00000000000
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx
+++ /dev/null
@@ -1,235 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useParams } from 'common'
-import { useEffect } from 'react'
-import { toast } from 'sonner'
-
-import {
- ScaffoldSection,
- ScaffoldSectionContent,
- ScaffoldSectionDetail,
-} from 'components/layouts/Scaffold'
-import AlertError from 'components/ui/AlertError'
-import { FormActions } from 'components/ui/Forms/FormActions'
-import { FormPanel } from 'components/ui/Forms/FormPanel'
-import { FormSection, FormSectionContent } from 'components/ui/Forms/FormSection'
-import NoPermission from 'components/ui/NoPermission'
-import PartnerManagedResource from 'components/ui/PartnerManagedResource'
-import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { useOrganizationCustomerProfileQuery } from 'data/organizations/organization-customer-profile-query'
-import { useOrganizationCustomerProfileUpdateMutation } from 'data/organizations/organization-customer-profile-update-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { Form, Input, Listbox } from 'ui'
-import { COUNTRIES } from './BillingAddress.constants'
-
-const BillingAddress = () => {
- const { slug } = useParams()
- const selectedOrganization = useSelectedOrganization()
-
- const canReadBillingAddress = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.customer'
- )
- const canUpdateBillingAddress = useCheckPermissions(
- PermissionAction.BILLING_WRITE,
- 'stripe.customer'
- )
-
- const { data, error, isLoading, isSuccess, isError } = useOrganizationCustomerProfileQuery(
- { slug },
- { enabled: canReadBillingAddress }
- )
- const { mutate: updateCustomerProfile, isLoading: isUpdating } =
- useOrganizationCustomerProfileUpdateMutation()
-
- const formId = 'billing-address-form'
- const { city, country, line1, line2, postal_code, state } = data?.address ?? {}
- const initialValues = { city, country, line1, line2, postal_code, state }
-
- const validate = (values: any) => {
- const errors = {} as any
- if (
- (values.line1 || values.line2 || values.postal_code || values.state || values.city) &&
- !values.country
- ) {
- errors['country'] = 'Please select a country'
- }
- if (
- (values.country || values.line2 || values.postal_code || values.state || values.city) &&
- !values.line1
- ) {
- errors['line1'] = 'Please provide an address line'
- }
- return errors
- }
-
- const onSubmit = async (values: any, { resetForm }: any) => {
- if (!slug) return console.error('Slug is required')
-
- const address = !values.line1 ? null : values
-
- updateCustomerProfile(
- { slug, address },
- {
- onSuccess: () => {
- toast.success('Successfully updated billing address')
- resetForm({ values, initialValues: values })
- },
- }
- )
- }
-
- return (
- <ScaffoldSection>
- <ScaffoldSectionDetail>
- <div className="sticky space-y-2 top-12 pr-3">
- <p className="text-foreground text-base m-0">Billing Address</p>
- <p className="text-sm text-foreground-light m-0">
- This will be reflected in every upcoming invoice, past invoices are not affected
- </p>
- </div>
- </ScaffoldSectionDetail>
- <ScaffoldSectionContent>
- {selectedOrganization?.managed_by !== undefined &&
- selectedOrganization?.managed_by !== 'supabase' ? (
- <PartnerManagedResource
- partner={selectedOrganization?.managed_by}
- resource="Billing Addresses"
- cta={{
- installationId: selectedOrganization?.partner_id,
- }}
- />
- ) : !canReadBillingAddress ? (
- <NoPermission resourceText="view this organization's billing address" />
- ) : (
- <>
- {isLoading && (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- )}
-
- {isError && (
- <AlertError
- subject="Failed to retrieve organization customer profile"
- error={error as any}
- />
- )}
-
- {isSuccess && (
- <Form
- validateOnBlur
- id={formId}
- initialValues={initialValues}
- validate={validate}
- onSubmit={onSubmit}
- >
- {({ values, initialValues, handleReset, resetForm }: any) => {
- const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
-
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- if (isSuccess && data !== undefined) {
- const { city, country, line1, line2, postal_code, state } =
- data?.address ?? {}
- const values = { city, country, line1, line2, postal_code, state }
- resetForm({ values, initialValues: values })
- }
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isSuccess])
-
- return (
- <FormPanel
- footer={
- <div className="flex py-4 px-8">
- <FormActions
- form={formId}
- isSubmitting={isUpdating}
- hasChanges={hasChanges}
- handleReset={handleReset}
- helper={
- !canUpdateBillingAddress
- ? "You need additional permissions to manage this organization's billing address"
- : undefined
- }
- />
- </div>
- }
- >
- <FormSection>
- <FormSectionContent fullWidth loading={false} className="!gap-2">
- <Input
- id="line1"
- name="line1"
- placeholder="Address line 1"
- disabled={!canUpdateBillingAddress}
- />
- <Input
- id="line2"
- name="line2"
- placeholder="Address line 2"
- disabled={!canUpdateBillingAddress}
- />
- <div className="flex space-x-2">
- <Listbox
- className="w-full"
- id="country"
- name="country"
- placeholder="Country"
- disabled={!canUpdateBillingAddress}
- >
- <Listbox.Option label="---" key="empty" value="">
- ---
- </Listbox.Option>
- {COUNTRIES.map((country) => (
- <Listbox.Option
- label={country.name}
- key={country.code}
- value={country.code}
- >
- {country.name}
- </Listbox.Option>
- ))}
- </Listbox>
- <Input
- className="w-full"
- id="postal_code"
- name="postal_code"
- placeholder="Postal code"
- disabled={!canUpdateBillingAddress}
- />
- </div>
- <div className="flex space-x-2">
- <Input
- className="w-full"
- id="city"
- name="city"
- placeholder="City"
- disabled={!canUpdateBillingAddress}
- />
- <Input
- className="w-full"
- id="state"
- name="state"
- placeholder="State"
- disabled={!canUpdateBillingAddress}
- />
- </div>
- </FormSectionContent>
- </FormSection>
- </FormPanel>
- )
- }}
- </Form>
- )}
- </>
- )}
- </ScaffoldSectionContent>
- </ScaffoldSection>
- )
-}
-
-export default BillingAddress
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
index 28b5d774ba8..699e4b85330 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx
@@ -11,19 +11,17 @@ import {
import AlertError from 'components/ui/AlertError'
import NoPermission from 'components/ui/NoPermission'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import SparkBar from 'components/ui/SparkBar'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import UpcomingInvoice from './UpcomingInvoice'
-import SparkBar from 'components/ui/SparkBar'
const BillingBreakdown = () => {
const { slug: orgSlug } = useParams()
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { isSuccess: isPermissionsLoaded, can: canReadSubscriptions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const {
data: subscription,
@@ -74,7 +72,7 @@ const BillingBreakdown = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadSubscriptions ? (
+ {isPermissionsLoaded && !canReadSubscriptions ? (
<NoPermission resourceText="view this organization's upcoming invoice" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.constants.ts b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingAddress.constants.ts
similarity index 100%
rename from apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.constants.ts
rename to apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingAddress.constants.ts
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx
new file mode 100644
index 00000000000..5082e90df99
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx
@@ -0,0 +1,178 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useMemo, useState } from 'react'
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import {
+ ScaffoldSection,
+ ScaffoldSectionContent,
+ ScaffoldSectionDetail,
+} from 'components/layouts/Scaffold'
+import AlertError from 'components/ui/AlertError'
+import NoPermission from 'components/ui/NoPermission'
+import PartnerManagedResource from 'components/ui/PartnerManagedResource'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+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 {
+ useAsyncCheckProjectPermissions,
+ useCheckPermissions,
+} from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { Button, Card, CardFooter, Form_Shadcn_ as Form } from 'ui'
+import { BillingCustomerDataForm } from './BillingCustomerDataForm'
+import { TAX_IDS } from './TaxID.constants'
+import { useBillingCustomerDataForm } from './useBillingCustomerDataForm'
+
+export const BillingCustomerData = () => {
+ const { slug } = useParams()
+ const selectedOrganization = useSelectedOrganization()
+
+ const { isSuccess: isPermissionsLoaded, can: canReadBillingCustomerData } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.customer')
+ const canUpdateBillingCustomerData = useCheckPermissions(
+ PermissionAction.BILLING_WRITE,
+ 'stripe.customer'
+ )
+
+ const {
+ data: customerProfile,
+ error,
+ isLoading,
+ isSuccess,
+ } = useOrganizationCustomerProfileQuery({ slug }, { enabled: canReadBillingCustomerData })
+
+ const {
+ data: taxId,
+ error: errorLoadingTaxId,
+ isLoading: isLoadingTaxId,
+ isSuccess: loadedTaxId,
+ } = useOrganizationTaxIdQuery({ slug })
+
+ const initialCustomerData = useMemo(
+ () => ({
+ ...customerProfile?.address,
+ 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 [isSubmitting, setIsSubmitting] = useState(false)
+
+ const { form, handleSubmit, handleReset, isDirty } = useBillingCustomerDataForm({
+ initialCustomerData,
+ onCustomerDataChange: async (data) => {
+ setIsSubmitting(true)
+
+ try {
+ await updateCustomerProfile({
+ slug,
+ address: data.address,
+ billing_name: data.billing_name,
+ })
+
+ await updateTaxId({ slug, taxId: data.tax_id })
+
+ toast.success('Successfully updated billing data')
+
+ setIsSubmitting(false)
+ } catch (error: any) {
+ toast.error(`Failed updating billing data: ${error.message}`)
+ setIsSubmitting(false)
+ }
+ },
+ })
+
+ const isSubmitDisabled = !isDirty || !canUpdateBillingCustomerData || isSubmitting
+
+ return (
+ <ScaffoldSection>
+ <ScaffoldSectionDetail>
+ <div className="sticky space-y-2 top-12 pr-3">
+ <p className="text-foreground text-base m-0">Billing Address &amp; Tax ID</p>
+ <p className="text-sm text-foreground-light m-0">
+ This will be reflected in every upcoming invoice, past invoices are not affected
+ </p>
+ </div>
+ </ScaffoldSectionDetail>
+ <ScaffoldSectionContent>
+ {selectedOrganization?.managed_by !== undefined &&
+ selectedOrganization?.managed_by !== 'supabase' ? (
+ <PartnerManagedResource
+ partner={selectedOrganization?.managed_by}
+ resource="Billing Addresses"
+ cta={{
+ installationId: selectedOrganization?.partner_id,
+ }}
+ />
+ ) : isPermissionsLoaded && !canReadBillingCustomerData ? (
+ <NoPermission resourceText="view this organization's billing address" />
+ ) : (
+ <>
+ {(isLoading || isLoadingTaxId) && (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ )}
+
+ {(error || errorLoadingTaxId) && (
+ <AlertError
+ subject="Failed to retrieve organization customer profile"
+ error={(error || errorLoadingTaxId) as any}
+ />
+ )}
+
+ {isSuccess && loadedTaxId && (
+ <Card>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(handleSubmit)}>
+ <BillingCustomerDataForm
+ className="p-8"
+ form={form}
+ disabled={!canUpdateBillingCustomerData}
+ />
+ <CardFooter className="border-t justify-end px-8">
+ {!canUpdateBillingCustomerData && (
+ <span className="text-sm text-foreground-lighter mr-auto">
+ You need additional permissions to manage this organization's billing
+ address
+ </span>
+ )}
+ <div className="flex items-center gap-2">
+ <Button type="default" onClick={handleReset} disabled={isSubmitDisabled}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ htmlType="submit"
+ disabled={isSubmitDisabled}
+ loading={isSubmitting}
+ >
+ Save
+ </Button>
+ </div>
+ </CardFooter>
+ </form>
+ </Form>
+ </Card>
+ )}
+ </>
+ )}
+ </ScaffoldSectionContent>
+ </ScaffoldSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataExistingOrgDialog.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataExistingOrgDialog.tsx
new file mode 100644
index 00000000000..9fac673f8fc
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataExistingOrgDialog.tsx
@@ -0,0 +1,215 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { Pencil } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { toast } from 'sonner'
+
+import AlertError from 'components/ui/AlertError'
+import NoPermission from 'components/ui/NoPermission'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+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 { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogSectionSeparator,
+ DialogTitle,
+ Form_Shadcn_ as Form,
+ Label_Shadcn_ as Label,
+} from 'ui'
+import { BillingCustomerDataForm } from './BillingCustomerDataForm'
+import { TAX_IDS } from './TaxID.constants'
+import { useBillingCustomerDataForm } from './useBillingCustomerDataForm'
+
+export const BillingCustomerDataExistingOrgDialog = () => {
+ const [open, setOpen] = useState(false)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+
+ const { slug } = useSelectedOrganization() ?? {}
+
+ const canReadBillingCustomerData = useCheckPermissions(
+ PermissionAction.BILLING_READ,
+ 'stripe.customer'
+ )
+
+ const canUpdateBillingCustomerData = useCheckPermissions(
+ PermissionAction.BILLING_WRITE,
+ 'stripe.customer'
+ )
+
+ const {
+ data: customerProfile,
+ error,
+ isLoading,
+ isSuccess,
+ } = useOrganizationCustomerProfileQuery({ slug }, { enabled: canReadBillingCustomerData })
+
+ const {
+ data: taxId,
+ error: errorTaxId,
+ isLoading: isLoadingTaxId,
+ isSuccess: isSuccessTaxId,
+ } = useOrganizationTaxIdQuery({ slug })
+
+ const initialCustomerData = useMemo(
+ () => ({
+ ...customerProfile?.address,
+ 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, handleReset, isDirty } = useBillingCustomerDataForm({
+ initialCustomerData,
+ onCustomerDataChange: async (data) => {
+ setIsSubmitting(true)
+
+ try {
+ await updateCustomerProfile({
+ slug,
+ address: data.address ?? undefined,
+ billing_name: data.billing_name,
+ })
+
+ await updateTaxId({ slug, taxId: data.tax_id })
+
+ toast.success('Successfully updated billing data')
+
+ setOpen(false)
+
+ setIsSubmitting(false)
+ } catch (error: any) {
+ toast.error(`Failed updating billing data: ${error.message}`)
+ setIsSubmitting(false)
+ }
+ },
+ })
+
+ const handleClose = () => {
+ handleReset()
+ setOpen(false)
+ }
+
+ const getAddressSummary = () => {
+ if (!customerProfile?.address?.line1) return 'Optionally add a billing address'
+
+ const parts = [
+ customerProfile?.billing_name,
+ customerProfile?.address?.line1,
+ customerProfile?.address?.city,
+ customerProfile?.address?.state,
+ customerProfile?.address?.country,
+ ].filter(Boolean)
+
+ return parts.join(', ')
+ }
+
+ const isSubmitDisabled = !isDirty || !canUpdateBillingCustomerData || isSubmitting
+
+ return (
+ <>
+ <div>
+ <Label htmlFor="billing-address-btn" className="text-foreground-light block mb-0">
+ Billing Address / Tax Id
+ </Label>
+ {!canReadBillingCustomerData ? (
+ <NoPermission resourceText="view this organization's billing address" />
+ ) : (
+ <>
+ {(isLoading || isLoadingTaxId) && (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ </div>
+ )}
+ {(error || errorTaxId) && (
+ <AlertError
+ subject="Failed to retrieve organization customer profile"
+ error={(error || errorTaxId) as any}
+ />
+ )}
+ {isSuccess && isSuccessTaxId && (
+ <div className="flex items-center justify-between">
+ <p className="text-xs text-foreground">{getAddressSummary()}</p>
+ <Button
+ id="billing-address-btn"
+ onClick={() => setOpen(true)}
+ type="text"
+ aria-label="Edit"
+ size={'tiny'}
+ className="w-8 h-8 p-0 text-foreground-light"
+ disabled={!canUpdateBillingCustomerData}
+ >
+ <Pencil size={14} strokeWidth={1.5} />
+ </Button>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!value) setOpen(false)
+ else setOpen(true)
+ }}
+ >
+ <DialogContent size={'large'}>
+ <DialogHeader>
+ <DialogTitle>Billing Address &amp; Tax Id</DialogTitle>
+ <DialogDescription>
+ This will be reflected in every upcoming invoice, past invoices are not affected
+ </DialogDescription>
+ </DialogHeader>
+ <DialogSectionSeparator />
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(handleSubmit)}>
+ <BillingCustomerDataForm
+ className="p-5"
+ form={form}
+ disabled={!canUpdateBillingCustomerData}
+ />
+ <DialogFooter className="justify-end">
+ {!canUpdateBillingCustomerData && (
+ <span className="text-sm text-foreground-lighter">
+ You need additional permissions to manage this organization's billing address
+ </span>
+ )}
+ <div className="flex items-center gap-2">
+ <Button type="default" onClick={handleClose}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ htmlType="submit"
+ disabled={isSubmitDisabled}
+ loading={isSubmitting}
+ >
+ Save
+ </Button>
+ </div>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsx
new file mode 100644
index 00000000000..7b7a8da1333
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataForm.tsx
@@ -0,0 +1,338 @@
+import { Check, ChevronsUpDown, X } from 'lucide-react'
+import { UseFormReturn } from 'react-hook-form'
+import { z } from 'zod'
+
+import { useState } from 'react'
+import {
+ Button,
+ cn,
+ Command_Shadcn_ as Command,
+ CommandEmpty_Shadcn_ as CommandEmpty,
+ CommandGroup_Shadcn_ as CommandGroup,
+ CommandInput_Shadcn_ as CommandInput,
+ CommandItem_Shadcn_ as CommandItem,
+ CommandList_Shadcn_ as CommandList,
+ FormControl_Shadcn_ as FormControl,
+ FormField_Shadcn_ as FormField,
+ FormMessage_Shadcn_ as FormMessage,
+ Input_Shadcn_ as Input,
+ Input_Shadcn_,
+ Popover_Shadcn_ as Popover,
+ PopoverContent_Shadcn_ as PopoverContent,
+ PopoverTrigger_Shadcn_ as PopoverTrigger,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { COUNTRIES } from './BillingAddress.constants'
+import { TAX_IDS } from './TaxID.constants'
+
+interface BillingCustomerDataFormProps {
+ form: UseFormReturn<BillingCustomerDataFormValues>
+ disabled?: boolean
+ className?: string
+}
+
+// Define the expected form values structure and validation schema
+export const BillingCustomerDataSchema = z
+ .object({
+ billing_name: z.string().min(3, 'Name must be at least 3 letters long'),
+ line1: z.string().optional(),
+ line2: z.string().optional(),
+ city: z.string().optional(),
+ state: z.string().optional(),
+ postal_code: z.string().optional(),
+ country: z.string().optional(),
+ tax_id_type: z.string(),
+ tax_id_value: z.string(),
+ tax_id_name: z.string(),
+ })
+ .refine(
+ (data) => {
+ // its fine to just set the name, but once any other field is set, requires full address
+ const hasAnyField = data.line1 || data.line2 || data.city || data.state || data.postal_code
+ // If any field has value, country and line1 must have values.
+ return !hasAnyField || (!!data.country && !!data.line1)
+ },
+ {
+ message: 'Country and Address line 1 are required if any other field is provided.',
+ path: ['line1'],
+ }
+ )
+ .refine((data) => !(!!data.line1 && !data.country), {
+ message: 'Please select a country',
+ path: ['country'],
+ })
+ .refine((data) => !(!!data.country && !data.line1), {
+ message: 'Please provide an address line 1',
+ path: ['line1'],
+ })
+
+export type BillingCustomerDataFormValues = z.infer<typeof BillingCustomerDataSchema>
+
+export const BillingCustomerDataForm = ({
+ form,
+ disabled = false,
+ className,
+}: BillingCustomerDataFormProps) => {
+ const [showCountriesPopover, setShowCountriesPopover] = useState(false)
+ const [showTaxIDsPopover, setShowTaxIDsPopover] = useState(false)
+
+ const onSelectTaxIdType = (name: string) => {
+ const selectedTaxIdOption = TAX_IDS.find((option) => option.name === name)
+ if (!selectedTaxIdOption) return
+ form.setValue('tax_id_type', selectedTaxIdOption.type)
+ form.setValue('tax_id_value', '')
+ form.setValue('tax_id_name', name)
+ }
+
+ const onRemoveTaxId = () => {
+ form.setValue('tax_id_name', '', { shouldDirty: true })
+ form.setValue('tax_id_type', '', { shouldDirty: true })
+ form.setValue('tax_id_value', '', { shouldDirty: true })
+ }
+
+ const { tax_id_name } = form.watch()
+ const selectedTaxId = TAX_IDS.find((option) => option.name === tax_id_name)
+
+ return (
+ <div className={cn('flex flex-col space-y-4', className)}>
+ <FormField
+ control={form.control}
+ name="billing_name"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <FormControl>
+ <Input {...field} placeholder="Name" disabled={disabled} />
+ </FormControl>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="line1"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <FormControl>
+ <Input {...field} placeholder="Address line 1" disabled={disabled} />
+ </FormControl>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="line2"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <FormControl>
+ <Input {...field} placeholder="Address line 2 (Optional)" disabled={disabled} />
+ </FormControl>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="country"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <Popover open={showCountriesPopover} onOpenChange={setShowCountriesPopover}>
+ <PopoverTrigger asChild>
+ <FormControl>
+ <Button
+ type="default"
+ role="combobox"
+ size="medium"
+ disabled={disabled}
+ className={cn(
+ 'w-full justify-between h-[34px]',
+ !field.value && 'text-muted'
+ )}
+ iconRight={
+ <ChevronsUpDown
+ className="ml-2 h-4 w-4 shrink-0 opacity-50"
+ strokeWidth={1.5}
+ />
+ }
+ >
+ {field.value
+ ? COUNTRIES.find((country) => country.code === field.value)?.name ||
+ 'Select country'
+ : 'Select country'}
+ </Button>
+ </FormControl>
+ </PopoverTrigger>
+ <PopoverContent sameWidthAsTrigger className="p-0" align="start">
+ <Command>
+ <CommandInput placeholder="Search country..." />
+ <CommandList>
+ <CommandEmpty>No country found.</CommandEmpty>
+ <CommandGroup>
+ {COUNTRIES.map((country) => (
+ <CommandItem
+ key={country.code}
+ value={country.name}
+ onSelect={() => {
+ form.setValue('country', country.code, {
+ shouldDirty: true,
+ shouldTouch: true,
+ shouldValidate: true,
+ })
+ setShowCountriesPopover(false)
+ }}
+ >
+ <Check
+ className={cn(
+ 'mr-2 h-4 w-4',
+ field.value === country.code ? 'opacity-100' : 'opacity-0'
+ )}
+ />
+ {country.name}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="postal_code"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <FormControl>
+ <Input {...field} placeholder="Postal code" disabled={disabled} />
+ </FormControl>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <FormField
+ control={form.control}
+ name="city"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <FormControl>
+ <Input {...field} placeholder="City" disabled={disabled} />
+ </FormControl>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="state"
+ render={({ field }: { field: any }) => (
+ <FormItemLayout hideMessage>
+ <FormControl>
+ <Input {...field} placeholder="State / Province" disabled={disabled} />
+ </FormControl>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-x-2 w-full items-end">
+ <FormField
+ name="tax_id_name"
+ control={form.control}
+ render={({ field }) => (
+ <FormItemLayout hideMessage layout="vertical" label="Tax ID">
+ <Popover open={showTaxIDsPopover} onOpenChange={setShowTaxIDsPopover}>
+ <PopoverTrigger asChild>
+ <FormControl>
+ <Button
+ type="default"
+ role="combobox"
+ size="medium"
+ disabled={disabled}
+ className={cn(
+ 'w-full justify-between h-[34px]',
+ !selectedTaxId && 'text-muted'
+ )}
+ iconRight={
+ <ChevronsUpDown
+ className="ml-2 h-4 w-4 shrink-0 opacity-50"
+ strokeWidth={1.5}
+ />
+ }
+ >
+ {selectedTaxId
+ ? `${selectedTaxId.country} - ${selectedTaxId.name}`
+ : 'Select tax ID'}
+ </Button>
+ </FormControl>
+ </PopoverTrigger>
+ <PopoverContent sameWidthAsTrigger className="p-0" align="start">
+ <Command>
+ <CommandInput placeholder="Search tax ID..." />
+ <CommandList>
+ <CommandEmpty>No tax ID found.</CommandEmpty>
+ <CommandGroup>
+ {TAX_IDS.sort((a, b) => a.country.localeCompare(b.country)).map(
+ (option) => (
+ <CommandItem
+ key={option.name}
+ value={`${option.country} - ${option.name}`}
+ onSelect={() => {
+ onSelectTaxIdType(option.name)
+ setShowTaxIDsPopover(false)
+ }}
+ >
+ <Check
+ className={cn(
+ 'mr-2 h-4 w-4',
+ selectedTaxId?.name === option.name ? 'opacity-100' : 'opacity-0'
+ )}
+ />
+ {option.country} - {option.name}
+ </CommandItem>
+ )
+ )}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ <FormMessage />
+ </FormItemLayout>
+ )}
+ />
+
+ {selectedTaxId && (
+ <div className="flex items-center space-x-2">
+ <FormField
+ name="tax_id_value"
+ control={form.control}
+ render={({ field }) => (
+ <FormItemLayout hideMessage className="w-full">
+ <FormControl>
+ <Input_Shadcn_
+ {...field}
+ placeholder={selectedTaxId?.placeholder}
+ disabled={disabled}
+ />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+
+ <Button type="text" className="px-1" icon={<X />} onClick={() => onRemoveTaxId()} />
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataNewOrgDialog.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataNewOrgDialog.tsx
new file mode 100644
index 00000000000..dd072469401
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerDataNewOrgDialog.tsx
@@ -0,0 +1,122 @@
+import { FocusTrap } from '@headlessui/react'
+import { Pencil } from 'lucide-react'
+import { useState } from 'react'
+
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogSectionSeparator,
+ DialogTitle,
+ DialogTrigger,
+ Form_Shadcn_ as Form,
+} from 'ui'
+import { BillingCustomerDataForm } from './BillingCustomerDataForm'
+import { FormCustomerData, useBillingCustomerDataForm } from './useBillingCustomerDataForm'
+
+interface BillingCustomerDataNewOrgDialogProps {
+ onCustomerDataChange: (data: FormCustomerData) => void
+}
+
+export const BillingCustomerDataNewOrgDialog = ({
+ onCustomerDataChange,
+}: BillingCustomerDataNewOrgDialogProps) => {
+ const [open, setOpen] = useState(false)
+
+ const handleDialogClose = () => {
+ setOpen(false)
+ }
+
+ const { form, handleSubmit, handleReset, isDirty } = useBillingCustomerDataForm({
+ onCustomerDataChange,
+ })
+
+ const handleClose = () => {
+ handleReset()
+ handleDialogClose()
+ }
+
+ const getAddressSummary = () => {
+ const { line1, city, state, country, billing_name } = form.getValues()
+
+ if (!line1) return 'Optionally add a billing address'
+
+ const parts = [billing_name, line1, city, state, country].filter(Boolean)
+
+ return parts.join(', ')
+ }
+
+ const isSubmitDisabled = !isDirty
+
+ return (
+ <div className="flex items-center justify-between">
+ <label className="text-sm text-foreground-light" htmlFor="billing-address-btn">
+ {getAddressSummary()}
+ </label>
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!value) handleDialogClose()
+ else setOpen(true)
+ }}
+ >
+ <DialogTrigger asChild>
+ <Button
+ id="billing-address-btn"
+ onClick={() => setOpen(true)}
+ type="text"
+ aria-label="Edit"
+ size={'tiny'}
+ className="w-8 h-8 p-0 text-foreground-light"
+ >
+ <Pencil size={14} strokeWidth={1.5} />
+ </Button>
+ </DialogTrigger>
+ <DialogContent size="large">
+ <DialogHeader>
+ <DialogTitle>Billing Address &amp; Tax Id</DialogTitle>
+ </DialogHeader>
+ <DialogSectionSeparator />
+ {/*
+ [Joshen] There's something odd going on with using Dialog and RHF FormField here
+ where the focus keeps going to the Dialog when tabbing across the input fields, hence the FocusTrap
+ What's weirder is that once you've cycled the focus through all the inputs at least once, the focus
+ then no longer goes to the Dialog thereafter
+ FWIW it's likely happening across the dashboard whereever we're using Dialog and FormField
+ */}
+ <FocusTrap>
+ <Form {...form}>
+ <form
+ id="new-org-billing-data-form"
+ onSubmit={(e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ form.handleSubmit(handleSubmit)(e)
+
+ // Only close the dialog if the form is valid
+ if (!Object.keys(form.formState.errors).length) {
+ handleDialogClose()
+ }
+ }}
+ >
+ <BillingCustomerDataForm className="p-5" form={form} />
+ <DialogFooter className="justify-end">
+ <div className="flex items-center gap-2">
+ <Button type="default" onClick={handleClose}>
+ Cancel
+ </Button>
+ <Button type="primary" htmlType="submit" disabled={isSubmitDisabled}>
+ Continue
+ </Button>
+ </div>
+ </DialogFooter>
+ </form>
+ </Form>
+ </FocusTrap>
+ </DialogContent>
+ </Dialog>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.constants.ts b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.constants.ts
similarity index 100%
rename from apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.constants.ts
rename to apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.constants.ts
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.utils.ts b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.utils.ts
similarity index 100%
rename from apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.utils.ts
rename to apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.utils.ts
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/useBillingCustomerDataForm.ts b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/useBillingCustomerDataForm.ts
new file mode 100644
index 00000000000..aef1e286377
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/useBillingCustomerDataForm.ts
@@ -0,0 +1,131 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useEffect } from 'react'
+import { useForm } from 'react-hook-form'
+
+import { BillingCustomerDataFormValues, BillingCustomerDataSchema } from './BillingCustomerDataForm'
+import { TAX_IDS } from './TaxID.constants'
+import { sanitizeTaxIdValue } from './TaxID.utils'
+import { components } from 'api-types'
+
+export type FormCustomerData = {
+ address: components['schemas']['CustomerResponse']['address'] | undefined
+ billing_name: string
+ tax_id: components['schemas']['TaxIdResponse']['tax_id'] | null
+}
+
+interface UseBillingAddressFormProps {
+ initialCustomerData?: Partial<BillingCustomerDataFormValues> | null
+ onCustomerDataChange: (data: FormCustomerData) => void
+}
+
+export function useBillingCustomerDataForm({
+ initialCustomerData,
+ onCustomerDataChange,
+}: UseBillingAddressFormProps) {
+ const form = useForm<BillingCustomerDataFormValues>({
+ resolver: zodResolver(BillingCustomerDataSchema),
+ defaultValues: {
+ billing_name: initialCustomerData?.billing_name || '',
+ line1: initialCustomerData?.line1 || '',
+ line2: initialCustomerData?.line2 || '',
+ city: initialCustomerData?.city || '',
+ state: initialCustomerData?.state || '',
+ postal_code: initialCustomerData?.postal_code || '',
+ country: initialCustomerData?.country || '',
+ tax_id_type: initialCustomerData?.tax_id_type || '',
+ tax_id_value: initialCustomerData?.tax_id_value || '',
+ tax_id_name: initialCustomerData?.tax_id_name || '',
+ },
+ })
+
+ // Update form when initialAddress changes
+ useEffect(() => {
+ if (initialCustomerData) {
+ form.reset({
+ billing_name: initialCustomerData.billing_name || '',
+ line1: initialCustomerData.line1 || '',
+ line2: initialCustomerData.line2 || '',
+ city: initialCustomerData.city || '',
+ state: initialCustomerData.state || '',
+ postal_code: initialCustomerData.postal_code || '',
+ country: initialCustomerData.country || '',
+ tax_id_type: initialCustomerData?.tax_id_type || '',
+ tax_id_value: initialCustomerData?.tax_id_value || '',
+ tax_id_name: initialCustomerData?.tax_id_name || '',
+ })
+ }
+ }, [initialCustomerData])
+
+ const handleSubmit = async (values: BillingCustomerDataFormValues) => {
+ const trimmedValues = Object.entries(values).reduce((acc, [key, value]) => {
+ acc[key as keyof BillingCustomerDataFormValues] =
+ typeof value === 'string' ? value.trim() : value
+ return acc
+ }, {} as BillingCustomerDataFormValues)
+
+ const addressPayload = !trimmedValues.line1 ? null : trimmedValues
+
+ const selectedTaxId = TAX_IDS.find((option) => option.name === values.tax_id_name)
+
+ onCustomerDataChange({
+ address: addressPayload
+ ? {
+ line1: trimmedValues.line1!,
+ line2: trimmedValues.line2,
+ city: trimmedValues.city,
+ state: trimmedValues.state,
+ postal_code: trimmedValues.postal_code,
+ country: trimmedValues.country!,
+ }
+ : undefined,
+ billing_name: trimmedValues.billing_name,
+ tax_id:
+ selectedTaxId && values.tax_id_type?.length && values.tax_id_value?.length
+ ? {
+ type: values.tax_id_type,
+ value: sanitizeTaxIdValue({
+ value: values.tax_id_value,
+ name: form.getValues().tax_id_name,
+ }),
+ country: selectedTaxId?.countryIso2,
+ }
+ : null,
+ })
+ }
+
+ const handleReset = () => {
+ if (initialCustomerData) {
+ form.reset({
+ billing_name: initialCustomerData.billing_name || '',
+ line1: initialCustomerData.line1 || '',
+ line2: initialCustomerData.line2 || '',
+ city: initialCustomerData.city || '',
+ state: initialCustomerData.state || '',
+ postal_code: initialCustomerData.postal_code || '',
+ country: initialCustomerData.country || '',
+ tax_id_type: initialCustomerData?.tax_id_type || '',
+ tax_id_value: initialCustomerData?.tax_id_value || '',
+ tax_id_name: initialCustomerData?.tax_id_name || '',
+ })
+ } else {
+ form.reset({
+ line1: '',
+ line2: '',
+ city: '',
+ state: '',
+ postal_code: '',
+ country: '',
+ tax_id_type: '',
+ tax_id_value: '',
+ tax_id_name: '',
+ })
+ }
+ }
+
+ return {
+ form,
+ handleSubmit,
+ handleReset,
+ isDirty: form.formState.isDirty,
+ }
+}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
index 0ee67a41a87..8af7d72ade4 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
@@ -18,7 +18,10 @@ import { FormSection, FormSectionContent } from 'components/ui/Forms/FormSection
import NoPermission from 'components/ui/NoPermission'
import { useOrganizationCustomerProfileQuery } from 'data/organizations/organization-customer-profile-query'
import { useOrganizationUpdateMutation } from 'data/organizations/organization-update-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import {
+ useAsyncCheckProjectPermissions,
+ useCheckPermissions,
+} from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { FormMessage_Shadcn_, Input_Shadcn_ } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
@@ -43,10 +46,8 @@ const BillingEmail = () => {
const { name, billing_email } = selectedOrganization ?? {}
const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
- const canReadBillingEmail = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { isSuccess: isPermissionsLoaded, can: canReadBillingEmail } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const { data: billingCustomer, isLoading: loadingBillingCustomer } =
useOrganizationCustomerProfileQuery({ slug }, { enabled: canReadBillingEmail })
@@ -107,7 +108,7 @@ const BillingEmail = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadBillingEmail ? (
+ {isPermissionsLoaded && !canReadBillingEmail ? (
<NoPermission resourceText="view this organization's email recipients" />
) : (
<Form {...form}>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
index 0c78de65c91..3109fc69ada 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingSettings.tsx
@@ -5,19 +5,18 @@ import {
ScaffoldDivider,
ScaffoldTitle,
} from 'components/layouts/Scaffold'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { cn } from 'ui'
-import { useOrgSubscriptionQuery } from '../../../../data/subscriptions/org-subscription-query'
import InvoicesSection from '../InvoicesSettings/InvoicesSection'
-import BillingAddress from './BillingAddress/BillingAddress'
import BillingBreakdown from './BillingBreakdown/BillingBreakdown'
+import { BillingCustomerData } from './BillingCustomerData/BillingCustomerData'
import BillingEmail from './BillingEmail'
import CostControl from './CostControl/CostControl'
import CreditBalance from './CreditBalance'
import PaymentMethods from './PaymentMethods/PaymentMethods'
import Subscription from './Subscription/Subscription'
-import TaxID from './TaxID/TaxID'
const BillingSettings = () => {
const {
@@ -109,13 +108,7 @@ const BillingSettings = () => {
<ScaffoldDivider />
<ScaffoldContainer id="address">
- <BillingAddress />
- </ScaffoldContainer>
-
- <ScaffoldDivider />
-
- <ScaffoldContainer id="taxId">
- <TaxID />
+ <BillingCustomerData />
</ScaffoldContainer>
</>
)}
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx
index 4b63791d318..fc8b417481f 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx
@@ -14,7 +14,7 @@ import AlertError from 'components/ui/AlertError'
import NoPermission from 'components/ui/NoPermission'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useFlag } from 'hooks/ui/useFlag'
import { BASE_PATH } from 'lib/constants'
import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
@@ -28,10 +28,8 @@ const CostControl = ({}: CostControlProps) => {
const { slug } = useParams()
const { resolvedTheme } = useTheme()
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { isSuccess: isPermissionsLoaded, can: canReadSubscriptions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const snap = useOrgSettingsPageStateSnapshot()
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
@@ -85,7 +83,7 @@ const CostControl = ({}: CostControlProps) => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadSubscriptions ? (
+ {isPermissionsLoaded && !canReadSubscriptions ? (
<NoPermission resourceText="update this organization's cost control" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx
index ab0cfee3adc..11e8d02f1be 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx
@@ -11,7 +11,7 @@ import { FormPanel } from 'components/ui/Forms/FormPanel'
import { FormSection, FormSectionContent } from 'components/ui/Forms/FormSection'
import NoPermission from 'components/ui/NoPermission'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useFlag } from 'hooks/ui/useFlag'
import { CreditTopUp } from './CreditTopUp'
@@ -19,10 +19,8 @@ const CreditBalance = () => {
const { slug } = useParams()
const creditTopUpEnabled = useFlag('creditTopUp')
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { isSuccess: isPermissionsLoaded, can: canReadSubscriptions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const {
data: subscription,
@@ -54,7 +52,7 @@ const CreditBalance = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadSubscriptions ? (
+ {isPermissionsLoaded && !canReadSubscriptions ? (
<NoPermission resourceText="view this organization's credits" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/PaymentMethods.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/PaymentMethods.tsx
index 788707ffb5b..15b85fa5ecf 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/PaymentMethods.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/PaymentMethods/PaymentMethods.tsx
@@ -19,7 +19,10 @@ import PartnerManagedResource from 'components/ui/PartnerManagedResource'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrganizationPaymentMethodsQuery } from 'data/organizations/organization-payment-methods-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import {
+ useAsyncCheckProjectPermissions,
+ useCheckPermissions,
+} from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { getURL } from 'lib/helpers'
import { Alert, Button } from 'ui'
@@ -43,10 +46,8 @@ const PaymentMethods = () => {
isSuccess,
} = useOrganizationPaymentMethodsQuery({ slug })
- const canReadPaymentMethods = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.payment_methods'
- )
+ const { isSuccess: isPermissionsLoaded, can: canReadPaymentMethods } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.payment_methods')
const canUpdatePaymentMethods = useCheckPermissions(
PermissionAction.BILLING_WRITE,
'stripe.payment_methods'
@@ -73,7 +74,7 @@ const PaymentMethods = () => {
installationId: selectedOrganization?.partner_id,
}}
/>
- ) : !canReadPaymentMethods ? (
+ ) : isPermissionsLoaded && !canReadPaymentMethods ? (
<NoPermission resourceText="view this organization's payment methods" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
index 89e9f0af6e6..a153e2cd2f8 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
@@ -26,9 +26,8 @@ import DowngradeModal from './DowngradeModal'
import { EnterpriseCard } from './EnterpriseCard'
import ExitSurveyModal from './ExitSurveyModal'
import MembersExceedLimitModal from './MembersExceedLimitModal'
-import SubscriptionPlanUpdateDialog from './SubscriptionPlanUpdateDialog'
+import { SubscriptionPlanUpdateDialog } from './SubscriptionPlanUpdateDialog'
import UpgradeSurveyModal from './UpgradeModal'
-import { PROJECT_STATUS } from 'lib/constants'
const PlanUpdateSidePanel = () => {
const router = useRouter()
@@ -305,7 +304,6 @@ const PlanUpdateSidePanel = () => {
billingPartner={billingPartner}
subscription={subscription}
projects={orgProjects}
- slug={slug}
currentPlanMeta={{
...availablePlans.find((p) => p.id === subscription?.plan?.id),
features:
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
index 919f88ef2c0..3c31b9a18c1 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx
@@ -11,7 +11,7 @@ import AlertError from 'components/ui/AlertError'
import NoPermission from 'components/ui/NoPermission'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useFlag } from 'hooks/ui/useFlag'
import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
import { Alert, Button } from 'ui'
@@ -25,10 +25,8 @@ const Subscription = () => {
const snap = useOrgSettingsPageStateSnapshot()
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { isSuccess: isPermissionsLoaded, can: canReadSubscriptions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const {
data: subscription,
@@ -61,7 +59,7 @@ const Subscription = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadSubscriptions ? (
+ {isPermissionsLoaded && !canReadSubscriptions ? (
<NoPermission resourceText="view this organization's subscription" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx
index 51d91402ff9..96349509809 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/SubscriptionPlanUpdateDialog.tsx
@@ -1,5 +1,5 @@
import { useQueryClient } from '@tanstack/react-query'
-import { Check, ExternalLink, InfoIcon } from 'lucide-react'
+import { Check, InfoIcon } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import tweets from 'shared-data/tweets'
@@ -10,29 +10,17 @@ import AlertError from 'components/ui/AlertError'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { organizationKeys } from 'data/organizations/keys'
import { OrganizationBillingSubscriptionPreviewResponse } from 'data/organizations/organization-billing-subscription-preview'
+import { ProjectInfo } from 'data/projects/projects-query'
import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
import { SubscriptionTier } from 'data/subscriptions/types'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { PRICING_TIER_PRODUCT_IDS, PROJECT_STATUS } from 'lib/constants'
import { formatCurrency } from 'lib/helpers'
-import {
- Badge,
- Button,
- Card,
- CardContent,
- Dialog,
- DialogContent,
- HoverCard,
- HoverCardContent,
- HoverCardTrigger,
- Table,
- TableBody,
- TableCell,
- TableRow,
-} from 'ui'
+import { Badge, Button, Dialog, DialogContent, Table, TableBody, TableCell, TableRow } from 'ui'
+import { Admonition } from 'ui-patterns'
import { InfoTooltip } from 'ui-patterns/info-tooltip'
+import { BillingCustomerDataExistingOrgDialog } from '../BillingCustomerData/BillingCustomerDataExistingOrgDialog'
import PaymentMethodSelection from './PaymentMethodSelection'
-import { ProjectInfo } from 'data/projects/projects-query'
-import { Admonition } from 'ui-patterns'
const getRandomTweet = () => {
const filteredTweets = tweets.filter((it) => it.text.length < 180)
@@ -71,12 +59,11 @@ interface Props {
billingPartner?: string
selectedOrganization: any
subscription: any
- slug?: string
currentPlanMeta: any
projects: ProjectInfo[]
}
-const SubscriptionPlanUpdateDialog = ({
+export const SubscriptionPlanUpdateDialog = ({
selectedTier,
onClose,
subscriptionPlanMeta,
@@ -89,11 +76,11 @@ const SubscriptionPlanUpdateDialog = ({
billingPartner,
selectedOrganization,
subscription,
- slug,
currentPlanMeta,
projects,
}: Props) => {
const queryClient = useQueryClient()
+ const { slug } = useSelectedOrganization() ?? {}
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>()
const [testimonialTweet, setTestimonialTweet] = useState(getRandomTweet())
@@ -167,6 +154,24 @@ const SubscriptionPlanUpdateDialog = ({
})
: []
+ // Calculate remaining days in current billing cycle
+ const now = Math.floor(Date.now() / 1000) // current time in seconds
+ const remainingSeconds = subscription?.current_period_end - now
+ const totalSeconds = subscription?.current_period_end - subscription?.current_period_start
+ const remainingRatio = remainingSeconds / totalSeconds
+
+ // Calculate prorated credit for current plan
+ const currentPlanMonthlyPrice = currentPlanMeta?.price ?? 0
+ const proratedCredit = currentPlanMonthlyPrice * remainingRatio
+
+ // Calculate new plan cost
+ const newPlanCost = subscriptionPlanMeta?.priceMonthly ?? 0
+
+ const customerBalance = ((subscription?.customer_balance ?? 0) / 100) * -1
+
+ // Calculate total charge (new plan - prorated credit)
+ const totalCharge = Math.max(0, newPlanCost - proratedCredit - customerBalance)
+
return (
<Dialog
open={selectedTier !== undefined && selectedTier !== 'tier_free'}
@@ -200,352 +205,266 @@ const SubscriptionPlanUpdateDialog = ({
)}
{subscriptionPreviewInitialized && (
<>
- <Table className="mt-2 mb-4 text-foreground-light">
- <TableBody>
- {(() => {
- // Calculate remaining days in current billing cycle
- const now = Math.floor(Date.now() / 1000) // current time in seconds
- const remainingSeconds = subscription?.current_period_end - now
- const totalSeconds =
- subscription?.current_period_end - subscription?.current_period_start
- const remainingRatio = remainingSeconds / totalSeconds
-
- // Calculate prorated credit for current plan
- const currentPlanMonthlyPrice = currentPlanMeta?.price ?? 0
- const proratedCredit = currentPlanMonthlyPrice * remainingRatio
-
- // Calculate new plan cost
- const newPlanCost = subscriptionPlanMeta?.priceMonthly ?? 0
-
- const customerBalance = ((subscription?.customer_balance ?? 0) / 100) * -1
-
- // Calculate total charge (new plan - prorated credit)
- const totalCharge = Math.max(
- 0,
- newPlanCost - proratedCredit - customerBalance
- )
-
- return (
+ <div className="mt-2 mb-4 text-foreground-light text-sm">
+ <div className="flex items-center justify-between gap-2 border-b border-muted">
+ <div className="py-2 pl-0 flex items-center gap-1">
+ <span>{subscriptionPlanMeta?.name} Plan</span>
+ <Badge variant={'brand'} size={'small'} className="ml-1">
+ New
+ </Badge>
+ </div>
+ <div className="py-2 pr-0 text-right">{formatCurrency(newPlanCost)}</div>
+ </div>
+ {subscription?.plan?.id !== 'free' && (
+ <div className="flex items-center justify-between gap-2 border-b border-muted">
+ <div className="py-2 pl-0 flex items-center gap-1">
+ <span>Unused Time on {subscription?.plan?.name} Plan</span>
+ <InfoTooltip className="max-w-sm">
+ Your previous plan was charged upfront, so a plan change will prorate
+ any unused time in credits. If the prorated credits exceed the new plan
+ charge, the excessive credits are added to your organization for future
+ use.
+ </InfoTooltip>
+ </div>
+ <div className="py-2 pr-0 text-right">
+ -{formatCurrency(proratedCredit)}
+ </div>
+ </div>
+ )}
+
+ {/* Ignore rare case with negative balance (debt) */}
+ {customerBalance > 0 && (
+ <div className="flex items-center justify-between gap-2 border-b border-muted">
+ <div className="py-2 pl-0 flex items-center gap-1">
+ <span>Credits</span>
+ <InfoTooltip>
+ Credits will be used first before charging your card.
+ </InfoTooltip>
+ </div>
+ <div className="py-2 pr-0 text-right">
+ {formatCurrency(customerBalance)}
+ </div>
+ </div>
+ )}
+ <div className="flex items-center justify-between gap-2 border-b border-muted text-foreground">
+ <div className="py-2 pl-0">Charge today</div>
+ <div className="py-2 pr-0 text-right">
+ {formatCurrency(totalCharge)}
+ {subscription?.plan?.id !== 'free' && (
<>
- <TableRow>
- <TableCell className="py-2 pl-0 flex items-center gap-1">
- <span>{subscriptionPlanMeta?.name} Plan</span>
- <Badge variant={'brand'} size={'small'} className="ml-1">
- New
- </Badge>
- </TableCell>
- <TableCell className="py-2 pr-0 text-right">
- {formatCurrency(newPlanCost)}
- </TableCell>
- </TableRow>
- {subscription?.plan?.id !== 'free' && (
- <TableRow>
- <TableCell className="py-2 pl-0 flex items-center gap-1">
- <span>Unused Time on {subscription?.plan?.name} Plan</span>
- <InfoTooltip className="max-w-sm">
- Your previous plan was charged upfront, so a plan change will
- prorate any unused time in credits. If the prorated credits
- exceed the new plan charge, the excessive credits are added to
- your organization for future use.
- </InfoTooltip>
- </TableCell>
- <TableCell className="py-2 pr-0 text-right">
- -{formatCurrency(proratedCredit)}
- </TableCell>
- </TableRow>
+ {' '}
+ <Link
+ href={`/org/${slug}/billing#breakdown`}
+ className="text-sm text-brand hover:text-brand-600 transition"
+ target="_blank"
+ >
+ + current spend
+ </Link>
+ </>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center justify-between gap-2 text-foreground-lighter text-xs">
+ <div className="py-2 pl-0 flex items-center gap-1">
+ <span>Monthly invoice estimate</span>
+ <InfoTooltip side="right">
+ <div className="w-[520px] p-6">
+ <h3 className="text-base font-medium mb-2">Your new monthly invoice</h3>
+ <p className="prose text-xs mb-2">
+ Each paid project runs on a dedicated 24/7 server. First project uses
+ Compute Credits; additional ones cost $10+/month regardless of usage.{' '}
+ <Link
+ href={'/docs/guides/platform/manage-your-usage/compute'}
+ target="_blank"
+ >
+ Learn more
+ </Link>
+ .
+ </p>
+
+ {subscriptionPreviewError && (
+ <AlertError
+ error={subscriptionPreviewError}
+ subject="Failed to preview subscription."
+ />
)}
- {/* Ignore rare case with negative balance (debt) */}
- {customerBalance > 0 && (
- <TableRow>
- <TableCell className="py-2 pl-0 flex items-center gap-1">
- <span>Credits</span>
- <InfoTooltip>
- Credits will be used first before charging your card.
- </InfoTooltip>
- </TableCell>
- <TableCell className="py-2 pr-0 text-right">
- {formatCurrency(customerBalance)}
- </TableCell>
- </TableRow>
- )}
- <TableRow className="text-foreground">
- <TableCell className="py-2 pl-0 border-t">Charge today</TableCell>
- <TableCell className="py-2 pr-0 text-right border-t">
- {formatCurrency(totalCharge)}
- </TableCell>
- </TableRow>
- {subscription?.plan?.id !== 'free' && (
- <TableRow>
- <TableCell className="py-2 pl-0 flex items-center gap-1">
- <span>+ current cycle usage</span>
- <InfoTooltip className="max-w-sm">
- Changing your plan resets your billing cycle. If your previous
- billing cycle still has any outstanding usage charges, they will
- be added to your total charge today.
- </InfoTooltip>
- </TableCell>
- <TableCell className="py-2 pr-0 text-right">
- <Link
- href={`/org/${slug}/billing#breakdown`}
- className="text-sm text-brand hover:text-brand-600 transition"
- target="_blank"
- >
- View spend
- </Link>
- </TableCell>
- </TableRow>
+ {subscriptionPreviewIsLoading && (
+ <div className="space-y-2 p-6">
+ <span className="text-sm">Estimating monthly costs...</span>
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
)}
- </>
- )
- })()}
- </TableBody>
- </Table>
- <HoverCard>
- <HoverCardTrigger asChild>
- <Card className="cursor-help text-sm">
- <CardContent className="flex items-center gap-2 py-2 px-3 text-foreground-light hover:text-foreground">
- <InfoIcon strokeWidth={1.5} size={16} className="text-foreground-light" />
- Monthly invoice estimate is{' '}
- {formatCurrency(
- Math.round(
- subscriptionPreview?.breakdown.reduce(
- (prev: number, cur) => prev + cur.total_price,
- 0
- ) ?? 0
- )
- )}
- </CardContent>
- </Card>
- </HoverCardTrigger>
- <HoverCardContent className="w-[520px] p-6">
- <h3 className="text-md font-medium mb-2">Your new monthly invoice</h3>
-
- {subscriptionPreviewError && (
- <AlertError
- error={subscriptionPreviewError}
- subject="Failed to preview subscription."
- />
- )}
-
- {subscriptionPreviewIsLoading && (
- <div className="space-y-2 p-6">
- <span className="text-sm">Estimating monthly costs...</span>
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- )}
-
- {subscriptionPreviewInitialized && (
- <>
- <Table className="[&_tr:last-child]:border-t font-mono text-xs">
- <TableBody>
- {/* Non-compute items and Projects list */}
- {(() => {
- // Combine all compute-related projects
- const computeItems =
- subscriptionPreview?.breakdown?.filter(
- (item) =>
- item.description?.toLowerCase().includes('compute') &&
- item.breakdown?.length > 0
- ) || []
-
- const computeCreditsItem =
- subscriptionPreview?.breakdown?.find((item) =>
- item.description.startsWith('Compute Credits')
- ) ?? null
-
- const planItem = subscriptionPreview?.breakdown?.find((item) =>
- item.description?.toLowerCase().includes('plan')
- )
-
- const allProjects = computeItems.flatMap((item) =>
- item.breakdown.map((project) => ({
- ...project,
- computeType: item.description,
- computeCosts: Math.round(
- item.total_price / item.breakdown.length
- ),
- }))
- )
-
- const otherItems =
- subscriptionPreview?.breakdown?.filter(
- (item) =>
- !item.description?.toLowerCase().includes('compute') &&
- !item.description?.toLowerCase().includes('plan')
- ) || []
-
- const content = (
- <>
- {/* Combined projects section */}
- {allProjects.length > 0 && (
- <>
- <TableRow className="text-foreground-light">
- <TableCell className="!py-2 px-0">
- {planItem?.description}
- </TableCell>
- <TableCell className="text-right py-2 px-0">
- {formatCurrency(planItem?.total_price)}
- </TableCell>
- </TableRow>
-
- <TableRow className="text-foreground-light">
- <TableCell className="!py-2 px-0 flex items-center gap-1">
- <span>Compute</span>
- <InfoTooltip className="max-w-sm p-3">
- <p className="prose text-xs mb-2">
- Each project on a paid plan is a dedicated server
- running 24/7 with no pausing. The first project is
- covered by Compute Credits. Additional projects will
- incur compute costs starting at $10/month,
- independent of activity. See{' '}
- <Link
- href={
- '/docs/guides/platform/manage-your-usage/compute'
- }
- target="_blank"
+
+ {subscriptionPreviewInitialized && (
+ <>
+ <Table className="[&_tr:last-child]:border-t font-mono text-xs">
+ <TableBody>
+ {/* Non-compute items and Projects list */}
+ {(() => {
+ // Combine all compute-related projects
+ const computeItems =
+ subscriptionPreview?.breakdown?.filter(
+ (item) =>
+ item.description?.toLowerCase().includes('compute') &&
+ item.breakdown?.length > 0
+ ) || []
+
+ const computeCreditsItem =
+ subscriptionPreview?.breakdown?.find((item) =>
+ item.description.startsWith('Compute Credits')
+ ) ?? null
+
+ const planItem = subscriptionPreview?.breakdown?.find(
+ (item) => item.description?.toLowerCase().includes('plan')
+ )
+
+ const allProjects = computeItems.flatMap((item) =>
+ item.breakdown.map((project) => ({
+ ...project,
+ computeType: item.description,
+ computeCosts: Math.round(
+ item.total_price / item.breakdown.length
+ ),
+ }))
+ )
+
+ const otherItems =
+ subscriptionPreview?.breakdown?.filter(
+ (item) =>
+ !item.description?.toLowerCase().includes('compute') &&
+ !item.description?.toLowerCase().includes('plan')
+ ) || []
+
+ const content = (
+ <>
+ {/* Combined projects section */}
+ {allProjects.length > 0 && (
+ <>
+ <TableRow className="text-foreground-light">
+ <TableCell className="!py-2 px-0">
+ {planItem?.description}
+ </TableCell>
+ <TableCell className="text-right py-2 px-0">
+ {formatCurrency(planItem?.total_price)}
+ </TableCell>
+ </TableRow>
+
+ <TableRow className="text-foreground-light">
+ <TableCell className="!py-2 px-0 flex items-center gap-1">
+ <span>Compute</span>
+ </TableCell>
+ <TableCell className="text-right py-2 px-0">
+ {formatCurrency(
+ computeItems.reduce(
+ (sum: number, item) => sum + item.total_price,
+ 0
+ ) + (computeCreditsItem?.total_price ?? 0)
+ )}
+ </TableCell>
+ </TableRow>
+ {/* Show first 3 projects */}
+ {allProjects.map((project) => (
+ <TableRow
+ key={project.project_ref}
+ className="text-foreground-light"
>
- docs
- </Link>
- .
- </p>
- {subscription?.plan?.id === 'free' && (
- <>
- <p className="text-xs text-foreground-light mb-3">
- Mixing paid and non-paid projects in a single
- organization is not possible. If you want
- projects to be on the Free Plan, use self-serve
- project transfers.
- </p>
- <div className="space-x-3">
- <Button
- asChild
- type="default"
- icon={<ExternalLink strokeWidth={1.5} />}
- >
- <Link
- href="/docs/guides/platform/manage-your-usage/compute"
- target="_blank"
- rel="noreferrer"
- >
- How billing for Compute works
- </Link>
- </Button>
- <Button
- asChild
- type="default"
- icon={<ExternalLink strokeWidth={1.5} />}
- >
- <Link
- href="/docs/guides/platform/project-transfer"
- target="_blank"
- rel="noreferrer"
- >
- Project transfers
- </Link>
- </Button>
- </div>
- </>
+ <TableCell className="!py-2 px-0 pl-6">
+ {project.project_name} ({project.computeType}) |{' '}
+ {formatCurrency(project.computeCosts)}
+ </TableCell>
+ </TableRow>
+ ))}
+ {computeCreditsItem && (
+ <TableRow className="text-foreground-light">
+ <TableCell className="!py-2 px-0 pl-6">
+ Compute Credits |{' '}
+ {formatCurrency(computeCreditsItem.total_price)}
+ </TableCell>
+ </TableRow>
)}
- </InfoTooltip>
- </TableCell>
- <TableCell className="text-right py-2 px-0">
- {formatCurrency(
- computeItems.reduce(
- (sum: number, item) => sum + item.total_price,
- 0
- ) + (computeCreditsItem?.total_price ?? 0)
- )}
- </TableCell>
- </TableRow>
- {/* Show first 3 projects */}
- {allProjects.map((project) => (
- <TableRow
- key={project.project_ref}
- className="text-foreground-light"
- >
- <TableCell className="!py-2 px-0 pl-6">
- {project.project_name} ({project.computeType}) |{' '}
- {formatCurrency(project.computeCosts)}
- </TableCell>
- </TableRow>
- ))}
- {computeCreditsItem && (
- <TableRow className="text-foreground-light">
- <TableCell className="!py-2 px-0 pl-6">
- Compute Credits |{' '}
- {formatCurrency(computeCreditsItem.total_price)}
- </TableCell>
- </TableRow>
+ </>
+ )}
+
+ {/* Non-compute items */}
+ {otherItems.map((item) => (
+ <TableRow
+ key={item.description}
+ className="text-foreground-light"
+ >
+ <TableCell className="text-xs py-2 px-0">
+ <div className="flex items-center gap-1">
+ <span>{item.description ?? 'Unknown'}</span>
+ {item.breakdown.length > 0 && (
+ <InfoTooltip className="max-w-sm">
+ <p>Projects using {item.description}:</p>
+ <ul className="ml-6 list-disc">
+ {item.breakdown.map((breakdown) => (
+ <li
+ key={`${item.description}-breakdown-${breakdown.project_ref}`}
+ >
+ {breakdown.project_name}
+ </li>
+ ))}
+ </ul>
+ </InfoTooltip>
+ )}
+ </div>
+ </TableCell>
+ <TableCell className="text-right text-xs py-2 px-0">
+ {formatCurrency(item.total_price)}
+ </TableCell>
+ </TableRow>
+ ))}
+ </>
+ )
+ return content
+ })()}
+
+ <TableRow>
+ <TableCell className="font-medium py-2 px-0">
+ Total per month (excluding other usage)
+ </TableCell>
+ <TableCell className="text-right font-medium py-2 px-0">
+ {formatCurrency(
+ Math.round(
+ subscriptionPreview?.breakdown?.reduce(
+ (prev, cur) => prev + cur.total_price,
+ 0
+ ) ?? 0
+ ) ?? 0
)}
- </>
- )}
-
- {/* Non-compute items */}
- {otherItems.map((item) => (
- <TableRow
- key={item.description}
- className="text-foreground-light"
- >
- <TableCell className="text-xs py-2 px-0">
- <div className="flex items-center gap-1">
- <span>{item.description ?? 'Unknown'}</span>
- {item.breakdown.length > 0 && (
- <InfoTooltip className="max-w-sm">
- <p>Projects using {item.description}:</p>
- <ul className="ml-6 list-disc">
- {item.breakdown.map((breakdown) => (
- <li
- key={`${item.description}-breakdown-${breakdown.project_ref}`}
- >
- {breakdown.project_name}
- </li>
- ))}
- </ul>
- </InfoTooltip>
- )}
- </div>
- </TableCell>
- <TableCell className="text-right text-xs py-2 px-0">
- {formatCurrency(item.total_price)}
- </TableCell>
- </TableRow>
- ))}
- </>
- )
- return content
- })()}
-
- <TableRow>
- <TableCell className="font-medium py-2 px-0">
- Total per month (excluding other usage)
- </TableCell>
- <TableCell className="text-right font-medium py-2 px-0">
- {formatCurrency(
- Math.round(
- subscriptionPreview?.breakdown?.reduce(
- (prev, cur) => prev + cur.total_price,
- 0
- ) ?? 0
- ) ?? 0
- )}
- </TableCell>
- </TableRow>
- </TableBody>
- </Table>
- </>
- )}
- </HoverCardContent>
- </HoverCard>
+ </TableCell>
+ </TableRow>
+ </TableBody>
+ </Table>
+ </>
+ )}
+ </div>
+ </InfoTooltip>
+ </div>
+ <div className="py-2 pr-0 text-right">
+ {formatCurrency(
+ Math.round(
+ subscriptionPreview?.breakdown.reduce(
+ (prev: number, cur) => prev + cur.total_price,
+ 0
+ ) ?? 0
+ )
+ )}
+ </div>
+ </div>
+ </div>
</>
)}
</div>
- <div className="mt-4 pt-4">
+ <div className="pt-6">
{!billingViaPartner ? (
- <div className="space-y-4">
+ <div className="space-y-2 mb-4">
+ <BillingCustomerDataExistingOrgDialog />
<PaymentMethodSelection
selectedPaymentMethod={selectedPaymentMethod}
onSelectPaymentMethod={setSelectedPaymentMethod}
@@ -586,8 +505,8 @@ const SubscriptionPlanUpdateDialog = ({
</div>
)}
- <div className="flex space-x-4">
- <Button type="default" onClick={onClose} className="flex-1">
+ <div className="flex space-x-2">
+ <Button type="default" size="medium" onClick={onClose} className="flex-1">
Cancel
</Button>
<Button
@@ -595,6 +514,7 @@ const SubscriptionPlanUpdateDialog = ({
type="primary"
onClick={onUpdateSubscription}
className="flex-1"
+ size="medium"
>
Confirm {planMeta?.change_type === 'downgrade' ? 'downgrade' : 'upgrade'}
</Button>
@@ -666,5 +586,3 @@ const SubscriptionPlanUpdateDialog = ({
</Dialog>
)
}
-
-export default SubscriptionPlanUpdateDialog
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx
deleted file mode 100644
index c374abacd19..00000000000
--- a/apps/studio/components/interfaces/Organization/BillingSettings/TaxID/TaxID.tsx
+++ /dev/null
@@ -1,261 +0,0 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useEffect } from 'react'
-import { useForm } from 'react-hook-form'
-import { toast } from 'sonner'
-import * as z from 'zod'
-
-import { useParams } from 'common'
-import {
- ScaffoldSection,
- ScaffoldSectionContent,
- ScaffoldSectionDetail,
-} from 'components/layouts/Scaffold'
-import AlertError from 'components/ui/AlertError'
-import { FormActions } from 'components/ui/Forms/FormActions'
-import NoPermission from 'components/ui/NoPermission'
-import Panel from 'components/ui/Panel'
-import PartnerManagedResource from 'components/ui/PartnerManagedResource'
-import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { useOrganizationTaxIdQuery } from 'data/organizations/organization-tax-id-query'
-import { useOrganizationTaxIdUpdateMutation } from 'data/organizations/organization-tax-id-update-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import {
- Button,
- FormControl_Shadcn_,
- FormField_Shadcn_,
- FormItem_Shadcn_,
- Form_Shadcn_,
- Input_Shadcn_,
- SelectContent_Shadcn_,
- SelectGroup_Shadcn_,
- SelectItem_Shadcn_,
- SelectTrigger_Shadcn_,
- SelectValue_Shadcn_,
- Select_Shadcn_,
-} from 'ui'
-import { TAX_IDS } from './TaxID.constants'
-import { checkTaxIdEqual, sanitizeTaxIdValue } from './TaxID.utils'
-import { X } from 'lucide-react'
-
-const TaxID = () => {
- const { slug } = useParams()
- const selectedOrganization = useSelectedOrganization()
-
- const { data: taxId, error, isLoading, isSuccess, isError } = useOrganizationTaxIdQuery({ slug })
- const { mutate: updateTaxId, isLoading: isUpdating } = useOrganizationTaxIdUpdateMutation({
- onSuccess: () => {
- toast.success('Successfully updated tax id')
- },
- })
-
- const FormSchema = z.object({ type: z.string(), value: z.string(), name: z.string() })
- const form = useForm<z.infer<typeof FormSchema>>({
- mode: 'onBlur',
- reValidateMode: 'onBlur',
- resolver: zodResolver(FormSchema),
- defaultValues: { type: '', value: '', name: '' },
- })
-
- const formattedTaxId = taxId
- ? {
- type: taxId.type,
- value: taxId.value,
- name:
- TAX_IDS.find(
- (option) => option.type === taxId.type && option.countryIso2 === taxId.country
- )?.name ?? '',
- }
- : { type: '', value: '', name: '' }
-
- const hasChanges = !checkTaxIdEqual(form.getValues(), formattedTaxId)
- const canReadTaxId = useCheckPermissions(PermissionAction.BILLING_READ, 'stripe.tax_ids')
- const canUpdateTaxId = useCheckPermissions(PermissionAction.BILLING_WRITE, 'stripe.tax_ids')
-
- useEffect(() => {
- if (isSuccess && formattedTaxId) {
- form.setValue('type', formattedTaxId.type)
- form.setValue('value', formattedTaxId.value)
- form.setValue('name', formattedTaxId.name)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isSuccess])
-
- const onSaveTaxId = async () => {
- if (!slug) return console.error('Slug is required')
-
- const { type, value } = form.getValues()
-
- if (type?.length && !value?.length) {
- form.setError('value', { message: 'Value is required' })
- return
- }
-
- updateTaxId({
- slug,
- taxId:
- type?.length && value?.length
- ? {
- type: type,
- value: sanitizeTaxIdValue({ value, name: form.getValues().name }),
- country: selectedTaxId?.countryIso2,
- }
- : null,
- })
- }
-
- const onResetTaxIds = () => {
- form.setValue('type', formattedTaxId.type)
- form.setValue('value', formattedTaxId.value)
- form.setValue('name', formattedTaxId.name)
- }
-
- const onSelectTaxIdType = (name: string) => {
- const selectedTaxIdOption = TAX_IDS.find((option) => option.name === name)
- if (!selectedTaxIdOption) return
- form.setValue('type', selectedTaxIdOption.type)
- form.setValue('value', '')
- form.setValue('name', name)
- }
-
- const onRemoveTaxId = () => {
- form.reset()
- }
-
- const { name } = form.watch()
-
- const selectedTaxId = TAX_IDS.find((option) => option.name === name)
-
- return (
- <ScaffoldSection>
- <ScaffoldSectionDetail>
- <div className="sticky space-y-2 top-12">
- <p className="text-foreground text-base m-0">Tax ID</p>
- <p className="text-sm text-foreground-light pr-4 m-0">
- Add a tax ID to your invoices. Changes only apply to future invoices.
- </p>
- <p className="text-sm text-foreground-light m-0">
- Make sure the tax ID looks exactly like the placeholder text.
- </p>
- </div>
- </ScaffoldSectionDetail>
- <ScaffoldSectionContent>
- {selectedOrganization?.managed_by !== undefined &&
- selectedOrganization?.managed_by !== 'supabase' ? (
- <PartnerManagedResource
- partner={selectedOrganization?.managed_by}
- resource="Tax IDs"
- cta={{
- installationId: selectedOrganization?.partner_id,
- }}
- />
- ) : !canReadTaxId ? (
- <NoPermission resourceText="view this organization's tax ID" />
- ) : (
- <>
- {isLoading && (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- )}
-
- {isError && (
- <AlertError error={error} subject="Failed to retrieve organization tax Id" />
- )}
-
- {isSuccess && (
- <Panel
- className="mb-8"
- footer={
- <FormActions
- form="tax-id-form"
- isSubmitting={isUpdating}
- hasChanges={hasChanges}
- handleReset={() => onResetTaxIds()}
- helper={
- !canUpdateTaxId
- ? "You need additional permissions to manage this organization's tax ID"
- : undefined
- }
- />
- }
- >
- <Form_Shadcn_ {...form}>
- <form
- id="tax-id-form"
- className="grid grid-cols-2 gap-2 w-full py-8 px-8 items-center"
- onSubmit={form.handleSubmit(() => onSaveTaxId())}
- >
- <FormField_Shadcn_
- name="name"
- control={form.control}
- render={({ field }) => (
- <FormItem_Shadcn_>
- <FormControl_Shadcn_>
- <Select_Shadcn_
- {...field}
- disabled={!canUpdateTaxId}
- value={field.value}
- onValueChange={(value) => onSelectTaxIdType(value)}
- >
- <SelectTrigger_Shadcn_>
- <SelectValue_Shadcn_ placeholder="None" />
- </SelectTrigger_Shadcn_>
- <SelectContent_Shadcn_>
- <SelectGroup_Shadcn_>
- {TAX_IDS.sort((a, b) => a.country.localeCompare(b.country)).map(
- (option) => (
- <SelectItem_Shadcn_ key={option.name} value={option.name}>
- {option.country} - {option.name}
- </SelectItem_Shadcn_>
- )
- )}
- </SelectGroup_Shadcn_>
- </SelectContent_Shadcn_>
- </Select_Shadcn_>
- </FormControl_Shadcn_>
- </FormItem_Shadcn_>
- )}
- />
-
- {selectedTaxId && (
- <div className="flex items-center space-x-2">
- <FormField_Shadcn_
- name="value"
- control={form.control}
- render={({ field }) => (
- <FormItem_Shadcn_ className="w-full">
- <FormControl_Shadcn_>
- <Input_Shadcn_
- {...field}
- placeholder={selectedTaxId?.placeholder}
- disabled={!canUpdateTaxId}
- />
- </FormControl_Shadcn_>
- </FormItem_Shadcn_>
- )}
- />
-
- <Button
- type="text"
- className="px-1"
- icon={<X />}
- onClick={() => onRemoveTaxId()}
- />
- </div>
- )}
- </form>
- </Form_Shadcn_>
- </Panel>
- )}
- </>
- )}
- </ScaffoldSectionContent>
- </ScaffoldSection>
- )
-}
-
-export default TaxID
diff --git a/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSection.tsx b/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSection.tsx
index 35d8c06199f..673df43cff6 100644
--- a/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSection.tsx
+++ b/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSection.tsx
@@ -5,11 +5,14 @@ import {
ScaffoldSectionDetail,
} from 'components/layouts/Scaffold'
import NoPermission from 'components/ui/NoPermission'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import InvoicesSettings from './InvoicesSettings'
const InvoicesSection = () => {
- const canReadInvoices = useCheckPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
+ const { isSuccess: isPermissionsLoaded, can: canReadInvoices } = useAsyncCheckProjectPermissions(
+ PermissionAction.BILLING_READ,
+ 'stripe.subscriptions'
+ )
return (
<ScaffoldSection>
@@ -24,7 +27,7 @@ const InvoicesSection = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadInvoices ? (
+ {isPermissionsLoaded && !canReadInvoices ? (
<NoPermission resourceText="view this organization's upcoming invoice" />
) : (
<InvoicesSettings />
diff --git a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
index 4542010b18d..08bb6eeb398 100644
--- a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
+++ b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx
@@ -1,6 +1,7 @@
import { PaymentElement, useElements, useStripe } from '@stripe/react-stripe-js'
import type { PaymentMethod } from '@stripe/stripe-js'
import { useQueryClient } from '@tanstack/react-query'
+import _ from 'lodash'
import { Edit2, ExternalLink, HelpCircle } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
@@ -16,6 +17,7 @@ import {
invalidateOrganizationsQuery,
useOrganizationsQuery,
} from 'data/organizations/organizations-query'
+import { useProjectsQuery } from 'data/projects/projects-query'
import { BASE_PATH, PRICING_TIER_LABELS_ORG } from 'lib/constants'
import { getURL } from 'lib/helpers'
import { useProfile } from 'lib/profile'
@@ -34,9 +36,9 @@ import {
TooltipContent,
TooltipTrigger,
} from 'ui'
-import { useProjectsQuery } from 'data/projects/projects-query'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import _ from 'lodash'
+import { BillingCustomerDataNewOrgDialog } from '../BillingSettings/BillingCustomerData/BillingCustomerDataNewOrgDialog'
+import { FormCustomerData } from '../BillingSettings/BillingCustomerData/useBillingCustomerDataForm'
const ORG_KIND_TYPES = {
PERSONAL: 'Personal',
@@ -101,6 +103,8 @@ const NewOrgForm = ({ onPaymentMethodReset }: NewOrgFormProps) => {
const [isOrgCreationConfirmationModalVisible, setIsOrgCreationConfirmationModalVisible] =
useState(false)
+ const [customerData, setCustomerData] = useState<FormCustomerData | null>(null)
+
const [formState, setFormState] = useState<FormState>({
plan: 'FREE',
name: '',
@@ -157,7 +161,8 @@ const NewOrgForm = ({ onPaymentMethodReset }: NewOrgFormProps) => {
router.push(`/new/${org.slug}?projectName=${prefilledProjectName}`)
}
},
- onError: () => {
+ onError: (data) => {
+ toast.error(`Failed to create organization: ${data.message}`)
resetPaymentMethod()
setNewOrgLoading(false)
},
@@ -182,6 +187,9 @@ const NewOrgForm = ({ onPaymentMethodReset }: NewOrgFormProps) => {
| 'tier_enterprise',
...(formState.kind == 'COMPANY' ? { size: formState.size } : {}),
payment_method: paymentMethodId,
+ billing_name: dbTier === 'FREE' ? undefined : customerData?.billing_name,
+ address: dbTier === 'FREE' ? undefined : customerData?.address,
+ tax_id: dbTier === 'FREE' ? undefined : customerData?.tax_id ?? undefined,
})
}
@@ -462,6 +470,21 @@ const NewOrgForm = ({ onPaymentMethodReset }: NewOrgFormProps) => {
</>
)}
+ {formState.plan !== 'FREE' && (
+ <Panel.Content className="border-b border-panel-border-interior-light dark:border-panel-border-interior-dark">
+ <div className="grid grid-cols-3">
+ <div className="col-span-1 flex space-x-2 text-sm items-center">
+ <Label_Shadcn_ htmlFor="spend-cap" className=" leading-normal">
+ Billing Address
+ </Label_Shadcn_>
+ </div>
+ <div className="col-span-2">
+ <BillingCustomerDataNewOrgDialog onCustomerDataChange={setCustomerData} />
+ </div>
+ </div>
+ </Panel.Content>
+ )}
+
{formState.plan !== 'FREE' && (
<Panel.Content>
{paymentMethod?.card !== undefined ? (
diff --git a/apps/studio/data/organizations/organization-create-mutation.ts b/apps/studio/data/organizations/organization-create-mutation.ts
index 77842d34cea..acd8c924c12 100644
--- a/apps/studio/data/organizations/organization-create-mutation.ts
+++ b/apps/studio/data/organizations/organization-create-mutation.ts
@@ -5,6 +5,7 @@ import { handleError, post } from 'data/fetchers'
import { permissionKeys } from 'data/permissions/keys'
import type { ResponseError } from 'types'
import { organizationKeys } from './keys'
+import type { components } from 'data/api'
export type OrganizationCreateVariables = {
name: string
@@ -12,6 +13,9 @@ export type OrganizationCreateVariables = {
size?: string
tier: 'tier_payg' | 'tier_pro' | 'tier_free' | 'tier_team' | 'tier_enterprise'
payment_method?: string
+ billing_name?: string
+ address?: components['schemas']['CreateOrganizationBody']['address']
+ tax_id?: components['schemas']['CreateOrganizationBody']['tax_id']
}
export async function createOrganization({
@@ -20,15 +24,20 @@ export async function createOrganization({
size,
tier,
payment_method,
+ address,
+ billing_name,
+ tax_id,
}: OrganizationCreateVariables) {
const { data, error } = await post('/platform/organizations', {
body: {
name,
- // @ts-ignore [Joshen] Generated API spec is wrong
kind,
size,
tier,
payment_method,
+ address,
+ billing_name,
+ tax_id,
},
})
diff --git a/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts b/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts
index ca7af88b5d8..ae62b58a1df 100644
--- a/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts
+++ b/apps/studio/data/organizations/organization-customer-profile-update-mutation.ts
@@ -7,13 +7,15 @@ import type { ResponseError } from 'types'
import { organizationKeys } from './keys'
export type OrganizationCustomerProfileUpdateVariables = {
- slug: string
+ slug?: string
address?: components['schemas']['CustomerResponse']['address']
+ billing_name: string
}
export async function updateOrganizationCustomerProfile({
slug,
address,
+ billing_name,
}: OrganizationCustomerProfileUpdateVariables) {
if (!slug) return console.error('Slug is required')
@@ -26,7 +28,7 @@ export async function updateOrganizationCustomerProfile({
slug,
},
},
- body: { address },
+ body: { address: address != null ? address : undefined, billing_name },
})
if (error) throw handleError(error)
return data
@@ -56,13 +58,14 @@ export const useOrganizationCustomerProfileUpdateMutation = ({
OrganizationCustomerProfileUpdateVariables
>((vars) => updateOrganizationCustomerProfile(vars), {
async onSuccess(data, variables, context) {
- const { address, slug } = variables
+ const { address, slug, billing_name } = variables
// We do not invalidate here as GET endpoint data is stale for 1-2 seconds, so we handle state manually
queryClient.setQueriesData(organizationKeys.customerProfile(slug), (prev: any) => {
if (!prev) return prev
return {
...prev,
+ billing_name,
address,
}
})
diff --git a/apps/studio/data/organizations/organization-tax-id-query.ts b/apps/studio/data/organizations/organization-tax-id-query.ts
index 6f47c864250..e672b0611aa 100644
--- a/apps/studio/data/organizations/organization-tax-id-query.ts
+++ b/apps/studio/data/organizations/organization-tax-id-query.ts
@@ -20,14 +20,10 @@ export async function getOrganizationTaxId(
const { data, error } = await get(`/platform/organizations/{slug}/tax-ids`, {
params: { path: { slug } },
signal,
- headers: {
- Version: '2',
- },
})
if (error) throw handleError(error)
- // @ts-ignore wrong typing due to mgmt api versioning
- return (data as components['schemas']['TaxIdV2Response']).tax_id
+ return (data as components['schemas']['TaxIdResponse']).tax_id
}
export type OrganizationTaxIdData = Awaited<ReturnType<typeof getOrganizationTaxId>>
diff --git a/apps/studio/data/organizations/organization-tax-id-update-mutation.ts b/apps/studio/data/organizations/organization-tax-id-update-mutation.ts
index 0af1701d696..14bec45b564 100644
--- a/apps/studio/data/organizations/organization-tax-id-update-mutation.ts
+++ b/apps/studio/data/organizations/organization-tax-id-update-mutation.ts
@@ -6,7 +6,7 @@ import type { ResponseError } from 'types'
import { organizationKeys } from './keys'
export type OrganizationTaxIdUpdateVariables = {
- slug: string
+ slug?: string
taxId: { type: string; value: string; country?: string } | null
}
diff --git a/apps/studio/hooks/misc/useCheckPermissions.ts b/apps/studio/hooks/misc/useCheckPermissions.ts
index bbff7a730b1..3c9e5597d81 100644
--- a/apps/studio/hooks/misc/useCheckPermissions.ts
+++ b/apps/studio/hooks/misc/useCheckPermissions.ts
@@ -3,11 +3,11 @@ import jsonLogic from 'json-logic-js'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { usePermissionsQuery } from 'data/permissions/permissions-query'
+import { useProjectDetailQuery } from 'data/projects/project-detail-query'
import { IS_PLATFORM } from 'lib/constants'
import type { Permission } from 'types'
import { useSelectedOrganization } from './useSelectedOrganization'
import { useSelectedProject } from './useSelectedProject'
-import { useProjectDetailQuery } from 'data/projects/project-detail-query'
const toRegexpString = (actionOrResource: string) =>
`^${actionOrResource.replace('.', '\\.').replace('%', '.*')}$`
@@ -80,12 +80,11 @@ export function useGetProjectPermissions(
projectRefOverride?: string,
enabled = true
) {
- const permissionsResult = usePermissionsQuery({
+ const { data, isLoading, isSuccess } = usePermissionsQuery({
enabled: permissionsOverride === undefined && enabled,
})
- const permissions =
- permissionsOverride === undefined ? permissionsResult.data : permissionsOverride
+ const permissions = permissionsOverride === undefined ? data : permissionsOverride
const organizationResult = useSelectedOrganization({
enabled: organizationSlugOverride === undefined && enabled,
@@ -109,7 +108,8 @@ export function useGetProjectPermissions(
permissions,
organizationSlug,
projectRef,
- isLoading: permissionsResult.isLoading,
+ isLoading,
+ isSuccess,
}
}
@@ -193,21 +193,25 @@ export function useAsyncCheckProjectPermissions(
organizationSlug: _organizationSlug,
projectRef: _projectRef,
isLoading: isPermissionsLoading,
+ isSuccess: isPermissionsSuccess,
} = useGetProjectPermissions(permissions, organizationSlug, projectRef, isLoggedIn)
if (!isLoggedIn)
return {
- isLoading: false,
+ isLoading: true,
+ isSuccess: false,
can: false,
}
if (!IS_PLATFORM)
return {
isLoading: false,
+ isSuccess: true,
can: true,
}
return {
isLoading: isPermissionsLoading,
+ isSuccess: isPermissionsSuccess,
can: doPermissionsCheck(allPermissions, action, resource, data, _organizationSlug, _projectRef),
}
}
diff --git a/apps/studio/pages/org/[slug]/billing.tsx b/apps/studio/pages/org/[slug]/billing.tsx
index c0abd1ebcfc..0684fbb3326 100644
--- a/apps/studio/pages/org/[slug]/billing.tsx
+++ b/apps/studio/pages/org/[slug]/billing.tsx
@@ -1,13 +1,10 @@
+import { useEffect } from 'react'
+
import { useParams } from 'common'
import { BillingSettings } from 'components/interfaces/Organization'
-import AppLayout from 'components/layouts/AppLayout/AppLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
-import { Loading } from 'components/ui/Loading'
-import { usePermissionsQuery } from 'data/permissions/permissions-query'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { useEffect } from 'react'
import {
ORG_SETTINGS_PANEL_KEYS,
useOrgSettingsPageStateSnapshot,
@@ -17,8 +14,6 @@ import type { NextPageWithLayout } from 'types'
const OrgBillingSettings: NextPageWithLayout = () => {
const { panel } = useParams()
const snap = useOrgSettingsPageStateSnapshot()
- const { isLoading: isLoadingPermissions } = usePermissionsQuery()
- const selectedOrganization = useSelectedOrganization()
useEffect(() => {
const allowedValues = ['subscriptionPlan', 'costControl']
@@ -29,15 +24,7 @@ const OrgBillingSettings: NextPageWithLayout = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [panel])
- return (
- <>
- {selectedOrganization === undefined && isLoadingPermissions ? (
- <Loading />
- ) : (
- <BillingSettings />
- )}
- </>
- )
+ return <BillingSettings />
}
OrgBillingSettings.getLayout = (page) => (
diff --git a/apps/studio/tests/components/Billing/TaxID.utils.test.ts b/apps/studio/tests/components/Billing/TaxID.utils.test.ts
index 68908eddbf1..40d2960b0b8 100644
--- a/apps/studio/tests/components/Billing/TaxID.utils.test.ts
+++ b/apps/studio/tests/components/Billing/TaxID.utils.test.ts
@@ -1,4 +1,4 @@
-import { sanitizeTaxIdValue } from 'components/interfaces/Organization/BillingSettings/TaxID/TaxID.utils'
+import { sanitizeTaxIdValue } from 'components/interfaces/Organization/BillingSettings/BillingCustomerData/TaxID.utils'
import { describe, test, expect } from 'vitest'
/**
diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.ts
index de596658974..547db303237 100644
--- a/packages/api-types/types/platform.d.ts
+++ b/packages/api-types/types/platform.d.ts
@@ -4183,6 +4183,7 @@ export interface components {
postal_code?: string
state?: string
}
+ billing_name?: string
}
Buffer: Record<string, never>
BulkDeleteUserContentResponse: {
@@ -4288,6 +4289,10 @@ export interface components {
session_id: string
token_name?: string
}
+ CreateCollectionBody: {
+ name: string
+ retention_days: number
+ }
CreateColumnBody: {
check?: string
comment?: string
@@ -4469,10 +4474,24 @@ export interface components {
id: string
}
CreateOrganizationBody: {
+ address?: {
+ city?: string
+ country: string
+ line1: string
+ line2?: string
+ postal_code?: string
+ state?: string
+ }
+ billing_name?: string
kind?: string
name: string
payment_method?: string
size?: string
+ tax_id?: {
+ country?: string
+ type: string
+ value: string
+ }
/** @enum {string} */
tier: 'tier_free' | 'tier_pro' | 'tier_payg' | 'tier_team' | 'tier_enterprise'
}
@@ -4783,6 +4802,7 @@ export interface components {
state?: string
}
balance: number
+ billing_name?: string
billing_via_partner: boolean
email: string
}
@@ -4856,7 +4876,6 @@ export interface components {
}
DeleteOAuthAppResponse: {
client_id: string
- client_secret_alias: string
created_at: string
icon?: string
id: string
@@ -5859,7 +5878,6 @@ export interface components {
app_id?: string
authorized_at?: string
client_id?: string
- client_secret_alias?: string
created_at?: string
created_by?: string
icon?: string
@@ -6815,7 +6833,6 @@ export interface components {
}
PutOAuthAppResponse: {
client_id: string
- client_secret_alias: string
created_at: string
icon?: string
id: string
@@ -7362,6 +7379,10 @@ export interface components {
description?: string
name?: string
}
+ UpdateCollectionBody: {
+ name: string
+ retention_days: number
+ }
UpdateColumnBody: {
check?: string
comment?: string
@@ -14151,7 +14172,7 @@ export interface operations {
}
requestBody: {
content: {
- 'application/json': components['schemas']['LFSource']
+ 'application/json': components['schemas']['CreateCollectionBody']
}
}
responses: {
@@ -14260,7 +14281,7 @@ export interface operations {
}
requestBody: {
content: {
- 'application/json': components['schemas']['LFSource']
+ 'application/json': components['schemas']['UpdateCollectionBody']
}
}
responses: {