The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: show tax in new org creation (#44553)
Ignacio Dobronich927d39926422
diff --git a/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/NewPaymentMethodElement.tsx b/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/NewPaymentMethodElement.tsxindex 26c3ab56137..3a5e6d6165e 100644--- a/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/NewPaymentMethodElement.tsx+++ b/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/NewPaymentMethodElement.tsx@@ -86,6 +86,7 @@ export const NewPaymentMethodElement = forwardRef(currentTaxId,customerName,onAddressChange,+ onAddressIncomplete,onTaxIdChange,}: {email?: string | null | undefined@@ -94,6 +95,7 @@ export const NewPaymentMethodElement = forwardRef(currentTaxId?: CustomerTaxId | nullcustomerName?: string | undefinedonAddressChange?: (address: CustomerAddress) => void+ onAddressIncomplete?: () => voidonTaxIdChange?: (taxId: CustomerTaxId | null) => void},ref@@ -304,11 +306,13 @@ export const NewPaymentMethodElement = forwardRef(key={`address-elements-${purchasingAsBusiness}`}onChange={(evt) => {setStripeAddress(evt.value)- if (onAddressChange && evt.complete) {- onAddressChange({+ if (evt.complete) {+ onAddressChange?.({...evt.value.address,line2: evt.value.address.line2 || undefined,})+ } else {+ onAddressIncomplete?.()}}}onReady={() => setFullyLoaded(true)}diff --git a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsxindex f9644e240d6..3be27cb5577 100644--- a/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx+++ b/apps/studio/components/interfaces/Organization/NewOrg/NewOrgForm.tsx@@ -2,17 +2,19 @@ import { zodResolver } from '@hookform/resolvers/zod'import { Elements } from '@stripe/react-stripe-js'import type { PaymentIntentResult, PaymentMethod, StripeElementsOptions } from '@stripe/stripe-js'import { loadStripe } from '@stripe/stripe-js'+import { useDebounce } from '@uidotdev/usehooks'import { LOCAL_STORAGE_KEYS } from 'common'import { groupBy } from 'lodash'import { HelpCircle } from 'lucide-react'import { useTheme } from 'next-themes'import { useRouter } from 'next/router'import { parseAsBoolean, parseAsString, useQueryStates } from 'nuqs'-import { useEffect, useMemo, useRef, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { SubmitHandler, useForm } from 'react-hook-form'import { toast } from 'sonner'import {Button,+ cn,Form_Shadcn_,FormControl_Shadcn_,FormField_Shadcn_,@@ -38,6 +40,7 @@ import SpendCapModal from '@/components/interfaces/Billing/SpendCapModal'import { InlineLink } from '@/components/ui/InlineLink'import Panel from '@/components/ui/Panel'import { useOrganizationCreateMutation } from '@/data/organizations/organization-create-mutation'+import { useOrganizationCreationPreview } from '@/data/organizations/organization-creation-preview'import { useOrganizationsQuery } from '@/data/organizations/organizations-query'import type { CustomerAddress, CustomerTaxId } from '@/data/organizations/types'import { useProjectsInfiniteQuery } from '@/data/projects/projects-infinite-query'@@ -46,6 +49,7 @@ import { useConfirmPendingSubscriptionCreateMutation } from '@/data/subscriptionimport { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'import { PRICING_TIER_LABELS_ORG, STRIPE_PUBLIC_KEY } from '@/lib/constants'+import { formatCurrency } from '@/lib/helpers'import { useProfile } from '@/lib/profile'const ORG_KIND_TYPES = {@@ -184,6 +188,56 @@ export const NewOrgForm = ({}}, [isSuccess, form, organizations?.length, user.profile?.username, user.isSuccess])+ const [latestAddress, setLatestAddress] = useState<CustomerAddress>()+ const [latestTaxId, setLatestTaxId] = useState<CustomerTaxId | null>()++ const billingAddress = useDebounce(latestAddress, 1000)+ const billingTaxId = useDebounce(latestTaxId, 1000)++ const handleAddressChange = useCallback((address: CustomerAddress) => {+ setLatestAddress({+ ...address,+ line2: address.line2 || undefined,+ })+ }, [])++ const handleAddressIncomplete = useCallback(() => {+ setLatestAddress(undefined)+ }, [])++ const handleTaxIdChange = useCallback((taxId: CustomerTaxId | null) => {+ setLatestTaxId(taxId)+ }, [])++ const selectedPlan = form.watch('plan')+ const selectedSpendCap = form.watch('spend_cap')++ useEffect(() => {+ if (selectedPlan === 'FREE' || !setupIntent) {+ setLatestAddress(undefined)+ setLatestTaxId(null)+ }+ }, [selectedPlan, setupIntent])++ const previewTier = useMemo(() => {+ if (selectedPlan === 'FREE') return undefined+ const dbTier = selectedPlan === 'PRO' && !selectedSpendCap ? 'PAYG' : selectedPlan+ return ('tier_' + dbTier.toLowerCase()) as 'tier_pro' | 'tier_payg' | 'tier_team'+ }, [selectedPlan, selectedSpendCap])++ const {+ data: creationPreview,+ isFetching: creationPreviewIsFetching,+ isSuccess: creationPreviewInitialized,+ } = useOrganizationCreationPreview(+ {+ tier: previewTier,+ address: billingAddress,+ taxId: billingTaxId ?? undefined,+ },+ { enabled: !!previewTier && !!billingAddress }+ )+const [newOrgLoading, setNewOrgLoading] = useState(false)const [paymentMethod, setPaymentMethod] = useState<PaymentMethod>()@@ -548,8 +602,57 @@ export const NewOrgForm = ({ref={paymentRef}email={user.profile?.primary_email}readOnly={newOrgLoading || paymentConfirmationLoading}+ onAddressChange={handleAddressChange}+ onAddressIncomplete={handleAddressIncomplete}+ onTaxIdChange={handleTaxIdChange}/></Elements>++ {creationPreviewInitialized && !!billingAddress && (+ <div+ className={cn(+ 'text-foreground-light text-sm transition-opacity mt-4',+ creationPreviewIsFetching && 'opacity-50'+ )}+ >+ {creationPreview.total !== creationPreview.plan_price && (+ <div className="flex items-center justify-between gap-2 border-b border-muted text-sm">+ <div className="py-2">Plan price</div>+ <div className="py-2 text-right tabular-nums" translate="no">+ {formatCurrency(creationPreview.plan_price)}+ </div>+ </div>+ )}++ {creationPreview.tax_status === 'calculated' &&+ creationPreview.tax &&+ creationPreview.tax.tax_amount > 0 && (+ <div className="flex items-center justify-between gap-2 border-b border-muted text-sm">+ <div className="py-2">+ Tax ({creationPreview.tax.tax_rate_percentage}%)+ </div>+ <div className="py-2 text-right tabular-nums" translate="no">+ {formatCurrency(creationPreview.tax.tax_amount)}+ </div>+ </div>+ )}++ {creationPreview.tax_status === 'failed' && (+ <div className="flex items-center justify-between gap-2 border-b border-muted text-sm">+ <div className="py-2 text-foreground-lighter">+ Tax could not be estimated and may be applied separately+ </div>+ </div>+ )}++ <div className="flex items-center justify-between gap-2 text-foreground text-base">+ <div className="py-2">Total due today</div>+ <div className="py-2 text-right tabular-nums" translate="no">+ {formatCurrency(creationPreview.total)}+ </div>+ </div>+ </div>+ )}</Panel.Content>)}diff --git a/apps/studio/data/organizations/keys.ts b/apps/studio/data/organizations/keys.tsindex 0fd0a9093c6..d41cec69d64 100644--- a/apps/studio/data/organizations/keys.ts+++ b/apps/studio/data/organizations/keys.ts@@ -26,6 +26,10 @@ export const organizationKeys = {['organizations', slug, 'project-claim', token] as const,availableRegions: (slug: string | undefined, cloudProvider: string, size?: string) =>['organizations', slug, 'available-regions', cloudProvider, size] as const,+ creationPreview: (+ tier: string | undefined,+ params?: { address?: Record<string, unknown>; taxId?: Record<string, unknown> }+ ) => ['organizations', 'creation-preview', tier, params] as const,previewCreditCode: (slug: string | undefined, code: string) =>['organizations', slug, 'preview-credit-code', code] as const,}diff --git a/apps/studio/data/organizations/organization-creation-preview.ts b/apps/studio/data/organizations/organization-creation-preview.tsnew file mode 100644index 00000000000..28e329701d5--- /dev/null+++ b/apps/studio/data/organizations/organization-creation-preview.ts@@ -0,0 +1,68 @@+import { keepPreviousData, useQuery } from '@tanstack/react-query'++import { organizationKeys } from './keys'+import type { CustomerAddress, CustomerTaxId } from './types'+import { handleError, post } from '@/data/fetchers'+import type { ResponseError, UseCustomQueryOptions } from '@/types'++export type OrganizationCreationPreviewVariables = {+ tier?: string+ address?: CustomerAddress+ taxId?: CustomerTaxId+}++export type OrganizationCreationPreviewResponse = {+ currency: string+ plan_price: number+ tax: {+ currency: string+ tax_amount: number+ tax_rate_percentage: number+ total_amount_excluding_tax: number+ total_amount_including_tax: number+ } | null+ tax_status: 'calculated' | 'not_applicable' | 'failed'+ total: number+}++export async function previewOrganizationCreation({+ tier,+ address,+ taxId,+}: OrganizationCreationPreviewVariables) {+ if (!tier) throw new Error('tier is required')++ const { data, error } = await post(`/platform/organizations/preview-creation`, {+ body: {+ tier: tier as 'tier_pro' | 'tier_payg' | 'tier_team',+ ...(address && { address }),+ ...(taxId && { tax_id: taxId }),+ },+ })++ if (error) handleError(error)++ return data as OrganizationCreationPreviewResponse+}++export type OrganizationCreationPreviewData = Awaited<+ ReturnType<typeof previewOrganizationCreation>+>++export const useOrganizationCreationPreview = <TData = OrganizationCreationPreviewData>(+ { tier, address, taxId }: OrganizationCreationPreviewVariables,+ {+ enabled = true,+ ...options+ }: UseCustomQueryOptions<OrganizationCreationPreviewData, ResponseError, TData> = {}+) =>+ useQuery<OrganizationCreationPreviewData, ResponseError, TData>({+ queryKey: organizationKeys.creationPreview(tier, {+ address: address as Record<string, unknown> | undefined,+ taxId: taxId as Record<string, unknown> | undefined,+ }),+ queryFn: () => previewOrganizationCreation({ tier, address, taxId }),+ enabled: enabled && typeof tier !== 'undefined',+ placeholderData: keepPreviousData,+ ...options,+ })