The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: code redemption in billing settings (#42377)
Kevin Grüneberged0162582840
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsxindex badd4a27576..f538d0b5070 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx@@ -1,5 +1,4 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useParams } from 'common'import {ScaffoldSection,@@ -12,6 +11,8 @@ import { FormSection, FormSectionContent } from 'components/ui/Forms/FormSectionimport NoPermission from 'components/ui/NoPermission'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'++import { CreditCodeRedemption } from './CreditCodeRedemption'import { CreditTopUp } from './CreditTopUp'const CreditBalance = () => {@@ -56,7 +57,14 @@ const CreditBalance = () => {<NoPermission resourceText="view this organization's credits" />) : (<FormPanel- footer={subscription?.billing_via_partner ? undefined : <CreditTopUp slug={slug} />}+ footer={+ subscription?.billing_via_partner ? undefined : (+ <div className="flex justify-end items-center py-4 px-8 gap-x-2">+ <CreditCodeRedemption slug={slug} />+ <CreditTopUp slug={slug} />+ </div>+ )+ }><FormSection><FormSectionContent fullWidth loading={isLoading}>diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsxnew file mode 100644index 00000000000..49c6c0b0d6b--- /dev/null+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsx@@ -0,0 +1,341 @@+import HCaptcha from '@hcaptcha/react-hcaptcha'+import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Alert, AlertDescription, AlertTitle } from '@ui/components/shadcn/ui/alert'+import { useFlag } from 'common'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { AlertCircle, Calendar, PartyPopper } from 'lucide-react'+import Link from 'next/link'+import { useRouter } from 'next/router'+import { useEffect, useRef, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import {+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogSection,+ DialogSectionSeparator,+ DialogTitle,+ DialogTrigger,+ Form_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Separator,+} from 'ui'+import { ShimmeringLoader } from 'ui-patterns'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { z } from 'zod'++import { useOrganizationCreditCodeRedemptionMutation } from '@/data/organizations/organization-credit-code-redemption-mutation'+import { useOrganizationCustomerProfileQuery } from '@/data/organizations/organization-customer-profile-query'+import useLatest from '@/hooks/misc/useLatest'+import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'++const FORM_ID = 'credit-code-redemption'++const FormSchema = z.object({+ code: z.coerce.string(),+})++type CreditCodeRedemptionForm = z.infer<typeof FormSchema>++export const CreditCodeRedemption = ({+ slug,+ modalVisible = false,+}: {+ slug: string | undefined+ modalVisible?: boolean+}) => {+ const { can: canRedeemCode, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissions(+ PermissionAction.BILLING_WRITE,+ 'stripe.subscriptions'+ )++ const redeemCodeEnabled = useFlag('redeemCodeEnabled')++ const { data: org, isLoading: isOrgLoading } = useSelectedOrganizationQuery({})++ const router = useRouter()++ const form = useForm<CreditCodeRedemptionForm>({+ resolver: zodResolver(FormSchema),+ defaultValues: {+ code: '',+ },+ })++ const { data: customerProfile, isLoading: isCustomerProfileLoading } =+ useOrganizationCustomerProfileQuery({ slug })++ useEffect(() => {+ if (!router.isReady) return++ const queryCode = router.query.code+ const codeFromParams = Array.isArray(queryCode) ? queryCode[0] : queryCode++ if (typeof codeFromParams === 'string' && codeFromParams.trim().length > 2) {+ form.setValue('code', codeFromParams)+ }+ }, [router.isReady, router.query.code, form])++ const [codeRedemptionModalVisible, setCodeRedemptionModalVisible] = useState(+ modalVisible || false+ )+ const captchaRef = useRef<HCaptcha>(null)+ const captchaTokenRef = useRef<string | null>(null)++ const {+ mutateAsync: redeemCode,+ isPending: redeemingCode,+ error: errorRedeemingCode,+ data: codeRedemptionResult,+ reset: resetCodeRedemption,+ } = useOrganizationCreditCodeRedemptionMutation()++ const resetCaptcha = () => {+ captchaTokenRef.current = null+ captchaRef.current?.resetCaptcha()+ }++ const initHcaptcha = async () => {+ let token = captchaTokenRef.current++ try {+ if (!token) {+ const captchaResponse = await captchaRef.current?.execute({ async: true })+ token = captchaResponse?.response ?? null+ captchaTokenRef.current = token+ return token+ }+ } catch (error) {+ return token+ }++ return token+ }+ const initHcaptchaRef = useLatest(initHcaptcha)++ useEffect(() => {+ if (codeRedemptionModalVisible) {+ initHcaptchaRef.current()+ }+ }, [codeRedemptionModalVisible, initHcaptchaRef])++ const onSubmit: SubmitHandler<CreditCodeRedemptionForm> = async ({ code }) => {+ const token = await initHcaptcha()++ await redeemCode(+ {+ slug,+ code,+ hcaptchaToken: token,+ },+ {+ onSuccess: (data) => {+ form.setValue('code', '')+ resetCaptcha()+ },+ }+ )+ }++ const onCodeRedemptionDialogVisibilityChange = (visible: boolean) => {+ setCodeRedemptionModalVisible(visible)+ if (!visible) {+ resetCodeRedemption()+ resetCaptcha()+ }+ }++ if (!redeemCodeEnabled) {+ return null+ }++ const codeRedemptionDisabled =+ !canRedeemCode || !isPermissionsLoaded || isOrgLoading || isCustomerProfileLoading++ return (+ <Dialog open={codeRedemptionModalVisible} onOpenChange={onCodeRedemptionDialogVisibilityChange}>+ {!modalVisible && (+ <DialogTrigger asChild>+ <ButtonTooltip+ type="default"+ className="pointer-events-auto"+ disabled={codeRedemptionDisabled}+ tooltip={{+ content: {+ side: 'bottom',+ text:+ isPermissionsLoaded && !canRedeemCode+ ? 'You need additional permissions to redeem codes'+ : undefined,+ },+ }}+ >+ Redeem Code+ </ButtonTooltip>+ </DialogTrigger>+ )}++ <DialogContent onInteractOutside={(e) => e.preventDefault()} size={'large'}>+ <HCaptcha+ ref={captchaRef}+ 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) => {+ captchaTokenRef.current = token+ if (document !== undefined) document.body.classList.remove('!pointer-events-auto')+ }}+ onExpire={() => {+ captchaTokenRef.current = null+ }}+ />++ {codeRedemptionResult ? (+ <div className="p-8">+ <div className="text-center flex items-center justify-center">+ <PartyPopper className="h-20 w-20" />+ </div>++ <div className="text-center">+ <p className="font-bold text-lg mt-2">Credits Redeemed!</p>+ </div>+ <Separator className="my-4" />+ <div className="flex w-full justify-center items-center">+ <div className="flex items-center space-x-1">+ <h4 className="opacity-50">$</h4>+ <h1 className="relative text-2xl">{codeRedemptionResult.amount_cents / 100}</h1>+ <h4 className="opacity-50"> credits applied</h4>+ </div>+ </div>++ {codeRedemptionResult.credits_expire_at && (+ <div className="mt-2 flex items-center justify-center gap-2 text-sm text-muted-foreground bg-muted/50 py-3 px-4 rounded-lg">+ <Calendar className="h-4 w-4" />+ <span>+ {'Expires on '}+ {new Date(codeRedemptionResult.credits_expire_at).toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ })}+ </span>+ </div>+ )}++ {org?.plan.id === 'free' && (+ <div className="mt-4 space-y-4">+ <Separator />+ <Button className="w-full" size={'medium'} type="primary" asChild>+ <Link href={`/org/${org?.slug}/billing?panel=subscriptionPlan`}>+ Upgrade Your Organization+ </Link>+ </Button>+ </div>+ )}+ </div>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>Redeem Code</DialogTitle>+ <DialogDescription className="space-y-2">+ <p className="prose text-sm">+ Redeem your credit code to add credits to your organization+ </p>+ </DialogDescription>+ </DialogHeader>++ <DialogSectionSeparator />++ <Form_Shadcn_ {...form}>+ {isOrgLoading || isCustomerProfileLoading ? (+ <div className="p-6 space-y-4">+ <ShimmeringLoader />+ <div className="flex space-x-4">+ <ShimmeringLoader className="w-1/2" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ </div>+ ) : (+ <form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>+ <DialogSection className="flex flex-col gap-2">+ <FormField_Shadcn_+ control={form.control}+ name="code"+ render={({ field }) => (+ <FormItemLayout label="Code" className="gap-1">+ <Input_Shadcn_+ {...field}+ className="uppercase"+ placeholder="ABCD-1234-EFGH-5678"+ />+ </FormItemLayout>+ )}+ />++ {customerProfile && customerProfile.balance < 0 && (+ <div className="mt-2 flex w-full justify-between items-center">+ <span>Current Balance</span>+ <div className="flex items-center space-x-1">+ <h4 className="opacity-50">$</h4>+ <h1 className="relative">{customerProfile.balance / -100}</h1>+ <h4 className="opacity-50">/credits</h4>+ </div>+ </div>+ )}++ <Alert variant={'default'} className="mt-4">+ <AlertCircle className="h-4 w-4" />+ <AlertTitle>Potential future charges</AlertTitle>+ <AlertDescription>+ Credits are applied to <strong>{org?.name}</strong> only and can't be shared+ or transferred to other organizations. Credits are automatically used toward+ invoices. When credits run out on a paid plan, your default payment method+ will be charged—your plan won't be downgraded automatically.+ </AlertDescription>+ </Alert>++ {errorRedeemingCode && (+ <Alert_Shadcn_ variant="destructive">+ <AlertCircle className="h-4 w-4 text-foreground-light" />+ <AlertTitle_Shadcn_>Code cannot be redeemed</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ {errorRedeemingCode?.message}+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}+ </DialogSection>++ <DialogFooter>+ <Button+ htmlType="submit"+ type="primary"+ loading={redeemingCode}+ disabled={codeRedemptionDisabled}+ >+ Redeem+ </Button>+ </DialogFooter>+ </form>+ )}+ </Form_Shadcn_>+ </>+ )}+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsxindex 21b00f6522a..167135bf1e3 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx@@ -1,16 +1,9 @@import HCaptcha from '@hcaptcha/react-hcaptcha'import { zodResolver } from '@hookform/resolvers/zod'import { Elements } from '@stripe/react-stripe-js'-import { loadStripe, PaymentIntentResult } from '@stripe/stripe-js'+import { PaymentIntentResult, loadStripe } 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { SubmitHandler, useForm } from 'react-hook-form'-import { toast } from 'sonner'-import { z } from 'zod'-import { getStripeElementsAppearanceOptions } from 'components/interfaces/Billing/Payment/Payment.utils'import { PaymentConfirmation } from 'components/interfaces/Billing/Payment/PaymentConfirmation'import { NO_PROJECT_MARKER } from 'components/interfaces/Support/SupportForm.utils'@@ -20,10 +13,15 @@ import { useOrganizationCreditTopUpMutation } from 'data/organizations/organizatimport { subscriptionKeys } from 'data/subscriptions/keys'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { STRIPE_PUBLIC_KEY } from 'lib/constants'+import { AlertCircle, Info } from 'lucide-react'+import { useTheme } from 'next-themes'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import { toast } from 'sonner'import {- Alert_Shadcn_,AlertDescription_Shadcn_,AlertTitle_Shadcn_,+ Alert_Shadcn_,Button,Dialog,DialogContent,@@ -34,11 +32,13 @@ import {DialogSectionSeparator,DialogTitle,DialogTrigger,- Form_Shadcn_,FormField_Shadcn_,+ Form_Shadcn_,Input_Shadcn_,} from 'ui'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { z } from 'zod'+import type { PaymentMethodElementRef } from '../../Billing/Payment/PaymentMethods/NewPaymentMethodElement'import PaymentMethodSelection from './Subscription/PaymentMethodSelection'@@ -192,160 +192,158 @@ export const CreditTopUp = ({ slug }: { slug: string | undefined }) => {}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 className="space-y-2">- <p className="prose text-sm">- 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.- </p>- <p className="prose text-sm">- For larger discounted credit packages, please reach out to us via{' '}- <SupportLink- queryParams={{- orgSlug: slug,- projectRef: NO_PROJECT_MARKER,- subject: 'I would like to inquire about larger credit packages',- category: SupportCategories.SALES_ENQUIRY,- }}- >- support- </SupportLink>- .- </p>- </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- ref={paymentMethodSelectionRef}- onSelectPaymentMethod={(pm) => form.setValue('paymentMethod', pm)}- selectedPaymentMethod={form.getValues('paymentMethod')}- readOnly={executingTopUp || paymentConfirmationLoading}- />- )}- />-- {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_>+ <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 className="space-y-2">+ <p className="prose text-sm">+ 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.+ </p>+ <p className="prose text-sm">+ For larger discounted credit packages, please reach out to us via{' '}+ <SupportLink+ queryParams={{+ orgSlug: slug,+ projectRef: NO_PROJECT_MARKER,+ subject: 'I would like to inquire about larger credit packages',+ category: SupportCategories.SALES_ENQUIRY,+ }}+ >+ support+ </SupportLink>+ .+ </p>+ </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>)}+ />- {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_>+ <FormField_Shadcn_+ control={form.control}+ name="paymentMethod"+ render={() => (+ <PaymentMethodSelection+ ref={paymentMethodSelectionRef}+ onSelectPaymentMethod={(pm) => form.setValue('paymentMethod', pm)}+ selectedPaymentMethod={form.getValues('paymentMethod')}+ readOnly={executingTopUp || paymentConfirmationLoading}+ />+ )}+ />++ {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_>- {errorInitiatingTopUp.message}+ 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_>)}- </DialogSection>-- {!paymentIntentConfirmation?.paymentIntent && (- <DialogFooter>- <Button- htmlType="submit"- type="primary"- loading={executingTopUp || paymentConfirmationLoading}- >- Top Up- </Button>- </DialogFooter>++ {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_>)}- </form>- </Form_Shadcn_>- {stripePromise && paymentIntentSecret && (- <Elements stripe={stripePromise} options={options}>- <PaymentConfirmation- paymentIntentSecret={paymentIntentSecret}- onPaymentIntentConfirm={(paymentIntentConfirmation) =>- paymentIntentConfirmed(paymentIntentConfirmation)- }- onLoadingChange={(loading) => setPaymentConfirmationLoading(loading)}- />- </Elements>- )}- </DialogContent>- </Dialog>- </div>+ </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)}+ />+ </Elements>+ )}+ </DialogContent>+ </Dialog>)}diff --git a/apps/studio/data/organizations/keys.ts b/apps/studio/data/organizations/keys.tsindex 7e5be236f76..95a59322621 100644--- a/apps/studio/data/organizations/keys.ts+++ b/apps/studio/data/organizations/keys.ts@@ -23,4 +23,6 @@ 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,+ previewCreditCode: (slug: string | undefined, code: string) =>+ ['organizations', slug, 'preview-credit-code', code] as const,}diff --git a/apps/studio/data/organizations/organization-credit-code-redemption-mutation.ts b/apps/studio/data/organizations/organization-credit-code-redemption-mutation.tsnew file mode 100644index 00000000000..20e8c5b8f79--- /dev/null+++ b/apps/studio/data/organizations/organization-credit-code-redemption-mutation.ts@@ -0,0 +1,79 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { handleError, post } from 'data/fetchers'+import type { ResponseError, UseCustomMutationOptions } from 'types'++import { subscriptionKeys } from '../subscriptions/keys'+import { organizationKeys } from './keys'++export type OrganizationCreditCodeRedemptionVariables = {+ code: string+ slug?: string+ hcaptchaToken?: string | null+}++export async function redeemCode({+ hcaptchaToken,+ code,+ slug,+}: OrganizationCreditCodeRedemptionVariables) {+ 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/redeem`, {+ params: {+ path: {+ slug,+ },+ },+ body: {+ hcaptcha_token: hcaptchaToken,+ code,+ },+ })++ if (error) handleError(error)++ return data+}++type RedeemCodeData = Awaited<ReturnType<typeof redeemCode>>++export const useOrganizationCreditCodeRedemptionMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<+ RedeemCodeData,+ ResponseError,+ OrganizationCreditCodeRedemptionVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<RedeemCodeData, ResponseError, OrganizationCreditCodeRedemptionVariables>({+ mutationFn: (vars) => redeemCode(vars),+ async onSuccess(data, variables, context) {+ const { slug, code } = variables++ await queryClient.invalidateQueries({ queryKey: organizationKeys.customerProfile(slug) })+ await queryClient.invalidateQueries({ queryKey: subscriptionKeys.orgSubscription(slug) })+ await queryClient.invalidateQueries({+ queryKey: organizationKeys.previewCreditCode(slug, code),+ })+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError !== undefined) {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organizations/organization-customer-profile-query.ts b/apps/studio/data/organizations/organization-customer-profile-query.tsindex da637ca5dc7..9c5f927c046 100644--- a/apps/studio/data/organizations/organization-customer-profile-query.ts+++ b/apps/studio/data/organizations/organization-customer-profile-query.ts@@ -50,7 +50,9 @@ export const useOrganizationCustomerProfileQuery = <TData = OrganizationCustomer// unnecessary requests, although this behaviour still needs handling on the UIconst { can: canReadCustomerProfile } = useAsyncCheckPermissions(PermissionAction.BILLING_READ,- 'stripe.customer'+ 'stripe.customer',+ undefined,+ { organizationSlug: slug })return useQuery<OrganizationCustomerProfileData, OrganizationCustomerProfileError, TData>({diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.tsindex e7312d2476a..a1c6f0b353f 100644--- a/packages/api-types/types/platform.d.ts+++ b/packages/api-types/types/platform.d.ts@@ -951,6 +951,40 @@ export interface paths {patch?: nevertrace?: never}+ '/platform/organizations/{slug}/billing/credits/preview-code': {+ parameters: {+ query?: never+ header?: never+ path?: never+ cookie?: never+ }+ get?: never+ put?: never+ /** Previews a code redemption */+ post: operations['OrgCreditsController_previewCode']+ delete?: never+ options?: never+ head?: never+ patch?: never+ trace?: never+ }+ '/platform/organizations/{slug}/billing/credits/redeem': {+ parameters: {+ query?: never+ header?: never+ path?: never+ cookie?: never+ }+ get?: never+ put?: never+ /** Redeems a credit code */+ post: operations['OrgCreditsController_redeemCode']+ delete?: never+ options?: never+ head?: never+ patch?: never+ trace?: never+ }'/platform/organizations/{slug}/billing/credits/top-up': {parameters: {query?: never@@ -5724,6 +5758,21 @@ export interface components {source: stringteamId?: string}+ CreditRedemptionPreviewResponse: {+ amount_cents: number+ /** Format: date-time */+ credits_expire_at: string | null+ validity_days: number | null+ }+ CreditRedemptionRequest: {+ code: string+ }+ CreditRedemptionResponse: {+ amount_cents: number+ /** Format: date-time */+ credits_expire_at: string | null+ validity_days: number | null+ }CreditsTopUpRequest: {address?: {city?: string | null@@ -13323,6 +13372,116 @@ export interface operations {}}}+ OrgCreditsController_previewCode: {+ parameters: {+ query?: never+ header?: never+ path: {+ /** @description Organization slug */+ slug: string+ }+ cookie?: never+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['CreditRedemptionRequest']+ }+ }+ responses: {+ /** @description Credit code details. */+ 200: {+ headers: {+ [name: string]: unknown+ }+ content: {+ 'application/json': components['schemas']['CreditRedemptionPreviewResponse']+ }+ }+ /** @description Unauthorized */+ 401: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Forbidden action */+ 403: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Rate limit exceeded */+ 429: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Failed to preview redemption code */+ 500: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ }+ }+ OrgCreditsController_redeemCode: {+ parameters: {+ query?: never+ header?: never+ path: {+ /** @description Organization slug */+ slug: string+ }+ cookie?: never+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['CreditRedemptionRequest']+ }+ }+ responses: {+ /** @description Credit code redeemed successfully. */+ 200: {+ headers: {+ [name: string]: unknown+ }+ content: {+ 'application/json': components['schemas']['CreditRedemptionResponse']+ }+ }+ /** @description Unauthorized */+ 401: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Forbidden action */+ 403: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Rate limit exceeded */+ 429: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ /** @description Failed to redeem credit code */+ 500: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ }+ }OrgCreditsController_createTopUp: {parameters: {query?: never