The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: credit top up (#32680)
Kevin Grünebergc791dd9e29b4
diff --git a/apps/studio/components/interfaces/Billing/Payment/AddPaymentMethodForm.tsx b/apps/studio/components/interfaces/Billing/Payment/AddPaymentMethodForm.tsxindex cc4f888b760..7f184986165 100644--- a/apps/studio/components/interfaces/Billing/Payment/AddPaymentMethodForm.tsx+++ b/apps/studio/components/interfaces/Billing/Payment/AddPaymentMethodForm.tsx@@ -111,7 +111,7 @@ const AddPaymentMethodForm = ({}return (- <form onSubmit={handleSubmit}>+ <div><Modal.ContentclassName={`transition ${isSaving ? 'pointer-events-none opacity-75' : 'opacity-100'}`}>@@ -147,16 +147,17 @@ const AddPaymentMethodForm = ({</Button><Buttonblock- htmlType="submit"+ htmlType="button"size="small"type="primary"loading={isSaving}disabled={isSaving}+ onClick={handleSubmit}>Add payment method</Button></Modal.Content>- </form>+ </div>)}diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsxindex 612a56bdae2..0275aaae5f7 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx@@ -82,7 +82,7 @@ const BillingAddress = () => {return (<ScaffoldSection><ScaffoldSectionDetail>- <div className="sticky space-y-2 top-12">+ <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 affecteddiff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsxindex 19ddf0ca50a..cb0489e80ba 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx@@ -39,7 +39,7 @@ const BillingBreakdown = () => {return (<ScaffoldSection><ScaffoldSectionDetail>- <div className="sticky space-y-2 top-12">+ <div className="sticky space-y-2 top-12 pr-3"><p className="text-foreground text-base m-0">Billing Breakdown</p><p className="text-sm text-foreground-light m-0">Current billing cycle: {billingCycleStart.format('MMM DD')} -{' '}diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsxindex 8cf402fb944..7c3341232e9 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx@@ -1,4 +1,5 @@import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'import {ScaffoldSection,@@ -6,14 +7,17 @@ import {ScaffoldSectionDetail,} from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import { FormPanel } from 'components/ui/Forms/FormPanel'+import { FormSection, FormSectionContent } from 'components/ui/Forms/FormSection'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 { Badge } from 'ui'-import { useOrgSubscriptionQuery } from '../../../../data/subscriptions/org-subscription-query'+import { useFlag } from 'hooks/ui/useFlag'+import { CreditTopUp } from './CreditTopUp'const CreditBalance = () => {const { slug } = useParams()+ const creditTopUpEnabled = useFlag('creditTopUp')const canReadSubscriptions = useCheckPermissions(PermissionAction.BILLING_READ,@@ -39,14 +43,12 @@ const CreditBalance = () => {return (<ScaffoldSection><ScaffoldSectionDetail>- <div className="sticky space-y-2 top-12">+ <div className="sticky space-y-2 top-12 pr-3"><div className="flex items-center space-x-2"><p className="text-foreground text-base m-0">Credit Balance</p>- {isCredit && <Badge>You have credits available</Badge>}- {isDebt && <Badge variant="destructive">Outstanding payments</Badge>}</div><p className="text-sm text-foreground-light m-0">- Charges will be deducted from your balance first+ Credits will be applied to future invoices, before charging your payment method.</p></div></ScaffoldSectionDetail>@@ -55,29 +57,30 @@ const CreditBalance = () => {<NoPermission resourceText="view this organization's credits" />) : (<>- {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}- />- )}+ <FormPanel footer={creditTopUpEnabled ? <CreditTopUp slug={slug} /> : null}>+ <FormSection>+ <FormSectionContent fullWidth loading={isLoading}>+ {isError && (+ <AlertError+ subject="Failed to retrieve organization customer profile"+ error={error}+ />+ )}- {isSuccess && (- <div className="flex items-end space-x-1">- {isDebt && <h4 className="opacity-50">-</h4>}- <h4 className="opacity-50">$</h4>- <h2 className="text-4xl relative top-[2px]">{balance}</h2>- {isCredit && <h4 className="opacity-50">/credits</h4>}- </div>- )}+ {isSuccess && (+ <div className="flex w-full justify-between items-center">+ <span>Balance</span>+ <div className="flex items-center space-x-1">+ {isDebt && <h4 className="opacity-50">-</h4>}+ <h4 className="opacity-50">$</h4>+ <h2 className="text-2xl relative">{balance}</h2>+ {isCredit && <h4 className="opacity-50">/credits</h4>}+ </div>+ </div>+ )}+ </FormSectionContent>+ </FormSection>+ </FormPanel></>)}</ScaffoldSectionContent>diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsxnew file mode 100644index 00000000000..2f8a5d0de82--- /dev/null+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx@@ -0,0 +1,364 @@+import HCaptcha from '@hcaptcha/react-hcaptcha'+import { zodResolver } from '@hookform/resolvers/zod'+import { Elements, useStripe } from '@stripe/react-stripe-js'+import { loadStripe, PaymentIntentResult } from '@stripe/stripe-js'+import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/constants'+import { useQueryClient } from '@tanstack/react-query'+import { AlertCircle, Info } from 'lucide-react'+import { useTheme } from 'next-themes'+import Link from 'next/link'+import { useCallback, useEffect, useMemo, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import { toast } from 'sonner'+import { z } from 'zod'++import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useOrganizationCreditTopUpMutation } from 'data/organizations/organization-credit-top-up-mutation'+import { subscriptionKeys } from 'data/subscriptions/keys'+import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'+import { STRIPE_PUBLIC_KEY } from 'lib/constants'+import { useIsHCaptchaLoaded } from 'stores/hcaptcha-loaded-store'+import {+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogSection,+ DialogSectionSeparator,+ DialogTitle,+ DialogTrigger,+ Form_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ LoadingLine,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import PaymentMethodSelection from './Subscription/PaymentMethodSelection'++const stripePromise = loadStripe(STRIPE_PUBLIC_KEY)++const FORM_ID = 'credit-top-up'++const FormSchema = z.object({+ amount: z.coerce+ .number()+ .gte(100, 'Amount must be between $100 - $999.')+ .lte(999, 'Amount must be between $100 - $999.')+ .int('Amount must be a whole number.'),+ paymentMethod: z.string(),+})++type CreditTopUpForm = z.infer<typeof FormSchema>++export const CreditTopUp = ({ slug }: { slug: string | undefined }) => {+ const { resolvedTheme } = useTheme()+ const queryClient = useQueryClient()++ const canTopUpCredits = useCheckPermissions(+ PermissionAction.BILLING_WRITE,+ 'stripe.subscriptions'+ )+ const isPermissionsLoaded = usePermissionsLoaded()++ const {+ mutateAsync: topUpCredits,+ isLoading: executingTopUp,+ error: errorInitiatingTopUp,+ } = useOrganizationCreditTopUpMutation({})++ const form = useForm<CreditTopUpForm>({+ resolver: zodResolver(FormSchema),+ defaultValues: {+ amount: 100,+ paymentMethod: '',+ },+ })++ const [topUpModalVisible, setTopUpModalVisible] = useState(false)+ const [paymentConfirmationLoading, setPaymentConfirmationLoading] = useState(false)+ const captchaLoaded = useIsHCaptchaLoaded()+ const [captchaToken, setCaptchaToken] = useState<string | null>(null)+ const [captchaRef, setCaptchaRef] = useState<HCaptcha | null>(null)++ const captchaRefCallback = useCallback((node: any) => {+ setCaptchaRef(node)+ }, [])++ const resetCaptcha = () => {+ setCaptchaToken(null)+ captchaRef?.resetCaptcha()+ }++ const initHcaptcha = async () => {+ if (topUpModalVisible && captchaRef && captchaLoaded) {+ let token = captchaToken++ try {+ if (!token) {+ const captchaResponse = await captchaRef.execute({ async: true })+ token = captchaResponse?.response ?? null+ setCaptchaToken(token)+ return token+ }+ } catch (error) {+ return token+ }++ return token+ }+ }++ useEffect(() => {+ initHcaptcha()+ }, [topUpModalVisible, captchaRef, captchaLoaded])++ const [paymentIntentSecret, setPaymentIntentSecret] = useState('')+ const [paymentIntentConfirmation, setPaymentIntentConfirmation] = useState<PaymentIntentResult>()++ const onSubmit: SubmitHandler<CreditTopUpForm> = async ({ amount, paymentMethod }) => {+ setPaymentIntentConfirmation(undefined)++ const token = await initHcaptcha()++ await topUpCredits(+ {+ slug,+ amount,+ payment_method_id: paymentMethod,+ hcaptchaToken: token,+ },+ {+ onSuccess: (data) => {+ if (data.status === 'succeeded') {+ onSuccessfulPayment()+ } else {+ setPaymentIntentSecret(data.payment_intent_secret || '')+ }++ resetCaptcha()+ },+ }+ )+ }++ const options = useMemo(() => {+ return {+ clientSecret: paymentIntentSecret,+ appearance: { theme: resolvedTheme?.includes('dark') ? 'night' : 'flat', labels: 'floating' },+ } as any+ }, [paymentIntentSecret, resolvedTheme])++ const onTopUpDialogVisibilityChange = (visible: boolean) => {+ setTopUpModalVisible(visible)+ if (!visible) {+ setCaptchaRef(null)+ setPaymentIntentConfirmation(undefined)+ setPaymentIntentSecret('')+ }+ }++ const paymentIntentConfirmed = (paymentIntentConfirmation: PaymentIntentResult) => {+ // Reset payment intent secret to ensure another attempt works as expected+ setPaymentIntentSecret('')+ setPaymentIntentConfirmation(paymentIntentConfirmation)++ if (paymentIntentConfirmation.paymentIntent?.status === 'succeeded') {+ onSuccessfulPayment()+ }+ }++ const onSuccessfulPayment = async () => {+ onTopUpDialogVisibilityChange(false)+ await queryClient.invalidateQueries(subscriptionKeys.orgSubscription(slug))+ toast.success(+ 'Successfully topped up balance. It may take a minute to reflect in your account.'+ )+ }++ return (+ <div className="flex items-center justify-end py-4 px-8">+ <Dialog open={topUpModalVisible} onOpenChange={(open) => onTopUpDialogVisibilityChange(open)}>+ <DialogTrigger asChild>+ <ButtonTooltip+ type="default"+ className="pointer-events-auto"+ disabled={!canTopUpCredits || !isPermissionsLoaded}+ tooltip={{+ content: {+ side: 'bottom',+ text:+ isPermissionsLoaded && !canTopUpCredits+ ? 'You need additional permissions to top up credits'+ : undefined,+ },+ }}+ >+ Top Up+ </ButtonTooltip>+ </DialogTrigger>++ <DialogContent onInteractOutside={(e) => e.preventDefault()}>+ <HCaptcha+ ref={captchaRefCallback}+ sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}+ size="invisible"+ onOpen={() => {+ // [Joshen] This is to ensure that hCaptcha popup remains clickable+ if (document !== undefined) document.body.classList.add('!pointer-events-auto')+ }}+ onClose={() => {+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')+ }}+ onVerify={(token) => {+ setCaptchaToken(token)+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')+ }}+ onExpire={() => {+ setCaptchaToken(null)+ }}+ />+ <DialogHeader>+ <DialogTitle>Top Up Credits</DialogTitle>+ <DialogDescription>+ On successful payment, an invoice will be issued and you'll be granted credits.+ Credits will be applied to future invoices only and are not refundable. The topped up+ credits do not expire.+ </DialogDescription>+ </DialogHeader>++ <DialogSectionSeparator />++ <Form_Shadcn_ {...form}>+ <form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>+ <DialogSection className="flex flex-col gap-2">+ <FormField_Shadcn_+ control={form.control}+ name="amount"+ render={({ field }) => (+ <FormItemLayout label="Amount (USD)" className="gap-1">+ <Input_Shadcn_ {...field} type="number" placeholder="100" />+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ control={form.control}+ name="paymentMethod"+ render={() => (+ <PaymentMethodSelection+ onSelectPaymentMethod={(pm) => form.setValue('paymentMethod', pm)}+ selectedPaymentMethod={form.getValues('paymentMethod')}+ />+ )}+ />++ <p className="prose text-sm">+ For larger discounted credit packages, please{' '}+ <Link+ href={`/support/new?slug=${slug}&subject=${encodeURIComponent('I would like to inquire about larger credit packages')}&category=${SupportCategories.BILLING}`}+ target="_blank"+ >+ reach out.+ </Link>+ </p>++ {paymentIntentConfirmation && paymentIntentConfirmation.error && (+ <Alert_Shadcn_ variant="destructive">+ <AlertCircle className="h-4 w-4" />+ <AlertTitle_Shadcn_>Error confirming payment</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ {paymentIntentConfirmation.error.message}+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ {paymentIntentConfirmation?.paymentIntent &&+ paymentIntentConfirmation.paymentIntent.status === 'processing' && (+ <Alert_Shadcn_ variant="default">+ <Info className="h-4 w-4" />+ <AlertTitle_Shadcn_>Payment processing</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ Your payment is processing and we are waiting for a confirmation from your+ card issuer. If the payment goes through you'll automatically be credited.+ Please check back later.+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ {errorInitiatingTopUp && (+ <Alert_Shadcn_ variant="destructive">+ <AlertCircle className="h-4 w-4" />+ <AlertTitle_Shadcn_>Error topping up balance</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ {errorInitiatingTopUp.message}+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ </DialogSection>++ {!paymentIntentConfirmation?.paymentIntent && (+ <DialogFooter>+ <Button+ htmlType="submit"+ type="primary"+ loading={executingTopUp || paymentConfirmationLoading}+ >+ Top Up+ </Button>+ </DialogFooter>+ )}+ </form>+ </Form_Shadcn_>+ {stripePromise && paymentIntentSecret && (+ <Elements stripe={stripePromise} options={options}>+ <PaymentConfirmation+ paymentIntentSecret={paymentIntentSecret}+ onPaymentIntentConfirm={(paymentIntentConfirmation) =>+ paymentIntentConfirmed(paymentIntentConfirmation)+ }+ onLoadingChange={(loading) => setPaymentConfirmationLoading(loading)}+ paymentMethodId={form.getValues().paymentMethod}+ />+ </Elements>+ )}+ </DialogContent>+ </Dialog>+ </div>+ )+}++const PaymentConfirmation = ({+ paymentIntentSecret,+ onPaymentIntentConfirm,+ onLoadingChange,+ paymentMethodId,+}: {+ paymentIntentSecret: string+ paymentMethodId: string+ onPaymentIntentConfirm: (response: PaymentIntentResult) => void+ onLoadingChange: (loading: boolean) => void+}) => {+ const stripe = useStripe()++ useEffect(() => {+ if (stripe && paymentIntentSecret) {+ onLoadingChange(true)+ stripe!+ .confirmCardPayment(paymentIntentSecret, { payment_method: paymentMethodId })+ .then((res) => {+ onPaymentIntentConfirm(res)+ onLoadingChange(false)+ })+ .catch((err) => {+ onLoadingChange(false)+ })+ }+ }, [paymentIntentSecret, stripe])++ return <LoadingLine loading={true} />+}diff --git a/apps/studio/data/organizations/organization-credit-top-up-mutation.ts b/apps/studio/data/organizations/organization-credit-top-up-mutation.tsnew file mode 100644index 00000000000..53d41c85955--- /dev/null+++ b/apps/studio/data/organizations/organization-credit-top-up-mutation.ts@@ -0,0 +1,72 @@+import { useMutation, UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { handleError, post } from 'data/fetchers'+import type { ResponseError } from 'types'++export type OrganizationCreditTopUpVariables = {+ payment_method_id: string+ amount: number+ slug?: string+ hcaptchaToken?: string | null+}++export async function topUpCredits({+ payment_method_id,+ amount,+ slug,+ hcaptchaToken,+}: OrganizationCreditTopUpVariables) {+ if (!payment_method_id) {+ throw new Error('Payment method id required')+ }++ if (!hcaptchaToken) {+ throw new Error('Captcha not submitted')+ }++ if (!slug) {+ throw new Error('Slug is required')+ }++ const { data, error } = await post(`/platform/organizations/{slug}/billing/credits/top-up`, {+ params: {+ path: {+ slug,+ },+ },+ body: { payment_method_id, amount, hcaptcha_token: hcaptchaToken },+ })++ if (error) handleError(error)++ return data+}++type OrganizationTaxIdUpdateData = Awaited<ReturnType<typeof topUpCredits>>++export const useOrganizationCreditTopUpMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<OrganizationTaxIdUpdateData, ResponseError, OrganizationCreditTopUpVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<OrganizationTaxIdUpdateData, ResponseError, OrganizationCreditTopUpVariables>(+ (vars) => topUpCredits(vars),+ {+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to top up credits: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.tsindex 0035062a5cd..47efd7a6e4b 100644--- a/packages/api-types/types/api.d.ts+++ b/packages/api-types/types/api.d.ts@@ -332,6 +332,10 @@ export interface paths {/** Retrieves a list of available Postgres versions available to the organization */post: operations['OrganizationSlugController_getAvailableImageVersions']}+ '/platform/organizations/{slug}/billing/credits/top-up': {+ /** Tops up the credit balance */+ post: operations['OrgCreditsController_createTopUp']+ }'/platform/organizations/{slug}/billing/invoices': {/** Gets invoices for the given organization */get: operations['OrgInvoicesController_getInvoices']@@ -3264,6 +3268,23 @@ export interface components {secret_access_key: stringsession_token: string}+ CreditsTopUpRequestDto: {+ amount: number+ hcaptcha_token: string+ payment_method_id: string+ }+ CreditsTopUpResponseDto: {+ payment_intent_secret?: string+ /** @enum {string} */+ status:+ | 'canceled'+ | 'processing'+ | 'requires_action'+ | 'requires_capture'+ | 'requires_confirmation'+ | 'requires_payment_method'+ | 'succeeded'+ }CustomerBillingAddress: {city?: stringcountry: string@@ -8785,6 +8806,34 @@ export interface operations {}}}+ /** Tops up the credit balance */+ OrgCreditsController_createTopUp: {+ parameters: {+ path: {+ slug: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['CreditsTopUpRequestDto']+ }+ }+ responses: {+ /** @description Top up has been successfully created. */+ 201: {+ content: {+ 'application/json': components['schemas']['CreditsTopUpResponseDto']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to top up credit balance */+ 500: {+ content: never+ }+ }+ }/** Gets invoices for the given organization */OrgInvoicesController_getInvoices: {parameters: {