Skip to content

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

Add flag disabled UI handler for code redeem page (#42591)

Joshen Lime803507a0dcf
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsx
index d34d78f8720..968e63bf7cc 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditCodeRedemption.tsx
@@ -1,19 +1,15 @@
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 { 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 {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
Button,
Dialog,
DialogContent,
@@ -24,19 +20,20 @@ import {
DialogSectionSeparator,
DialogTitle,
DialogTrigger,
- FormField_Shadcn_,
Form_Shadcn_,
+ FormField_Shadcn_,
Input_Shadcn_,
Separator,
} from 'ui'
-import { ShimmeringLoader } from 'ui-patterns'
+import { Admonition, ShimmeringLoader, TimestampInfo } from 'ui-patterns'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { z } from 'zod'
+import { UpgradePlanButton } from '@/components/ui/UpgradePlanButton'
import { useOrganizationCreditCodeRedemptionMutation } from '@/data/organizations/organization-credit-code-redemption-mutation'
import { useOrganizationCustomerProfileQuery } from '@/data/organizations/organization-customer-profile-query'
import { useOrganizationQuery } from '@/data/organizations/organization-query'
-import useLatest from '@/hooks/misc/useLatest'
+import { useLatest } from '@/hooks/misc/useLatest'
const FORM_ID = 'credit-code-redemption'
@@ -51,59 +48,49 @@ export const CreditCodeRedemption = ({
modalVisible = false,
onClose,
}: {
- slug: string | undefined
+ slug?: string
modalVisible?: boolean
onClose?: () => void
}) => {
+ const router = useRouter()
+ const redeemCodeEnabled = useFlag('redeemCodeEnabled')
+ const [codeRedemptionModalVisible, setCodeRedemptionModalVisible] = useState(
+ modalVisible || false
+ )
+
+ const { data: org, isLoading: isOrgLoading } = useOrganizationQuery({ slug })
+ const { data: customerProfile, isLoading: isCustomerProfileLoading } =
+ useOrganizationCustomerProfileQuery({ slug })
+
const { can: canRedeemCode, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissions(
PermissionAction.BILLING_WRITE,
'stripe.subscriptions',
undefined,
- {
- organizationSlug: slug,
- }
+ { organizationSlug: slug }
)
- const redeemCodeEnabled = useFlag('redeemCodeEnabled')
-
- const { data: org, isLoading: isOrgLoading } = useOrganizationQuery({ slug })
-
- const router = useRouter()
+ const captchaRef = useRef<HCaptcha>(null)
+ const captchaTokenRef = useRef<string | null>(null)
+ const codeRedemptionDisabled =
+ !canRedeemCode || !isPermissionsLoaded || isOrgLoading || isCustomerProfileLoading
const form = useForm<CreditCodeRedemptionForm>({
resolver: zodResolver(FormSchema),
- defaultValues: {
- code: '',
- },
+ 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,
+ mutate: redeemCode,
isPending: redeemingCode,
error: errorRedeemingCode,
data: codeRedemptionResult,
reset: resetCodeRedemption,
- } = useOrganizationCreditCodeRedemptionMutation()
+ } = useOrganizationCreditCodeRedemptionMutation({
+ onSuccess: () => {
+ form.setValue('code', '')
+ resetCaptcha()
+ },
+ })
const resetCaptcha = () => {
captchaTokenRef.current = null
@@ -128,28 +115,9 @@ export const CreditCodeRedemption = ({
}
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: () => {
- form.setValue('code', '')
- resetCaptcha()
- },
- }
- )
+ redeemCode({ slug, code, hcaptchaToken: token })
}
const onCodeRedemptionDialogVisibilityChange = (visible: boolean) => {
@@ -161,12 +129,24 @@ export const CreditCodeRedemption = ({
}
}
- if (!redeemCodeEnabled) {
- return null
- }
+ useEffect(() => {
+ if (!router.isReady) return
- const codeRedemptionDisabled =
- !canRedeemCode || !isPermissionsLoaded || isOrgLoading || isCustomerProfileLoading
+ 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])
+
+ useEffect(() => {
+ if (codeRedemptionModalVisible) {
+ initHcaptchaRef.current()
+ }
+ }, [codeRedemptionModalVisible, initHcaptchaRef])
+
+ if (!redeemCodeEnabled) return null
return (
<Dialog open={codeRedemptionModalVisible} onOpenChange={onCodeRedemptionDialogVisibilityChange}>
@@ -191,7 +171,7 @@ export const CreditCodeRedemption = ({
</DialogTrigger>
)}
- <DialogContent onInteractOutside={(e) => e.preventDefault()} size={'large'}>
+ <DialogContent size="medium" onInteractOutside={(e) => e.preventDefault()}>
<HCaptcha
ref={captchaRef}
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
@@ -212,21 +192,21 @@ export const CreditCodeRedemption = ({
}}
/>
- {codeRedemptionResult ? (
+ {!!codeRedemptionResult ? (
<div className="p-8">
<div className="text-center flex items-center justify-center">
- <PartyPopper className="h-20 w-20" />
+ <PartyPopper strokeWidth={1} className="h-14 w-14" />
</div>
<div className="text-center">
- <p className="font-bold text-lg mt-2">Credits Redeemed!</p>
+ <p className=" 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>
+ <p className="opacity-50 text-sm">$</p>
+ <p className="text-2xl">{codeRedemptionResult.amount_cents / 100}</p>
+ <p className="opacity-50 text-sm"> credits applied</p>
</div>
</div>
@@ -234,26 +214,29 @@ export const CreditCodeRedemption = ({
<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',
- })}
+ Expires on{' '}
+ <TimestampInfo
+ className="text-sm"
+ utcTimestamp={codeRedemptionResult.credits_expire_at}
+ labelFormat="MMMM DD, YYYY"
+ />
</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>
+ <div className="mt-4 flex flex-col gap-y-4">
+ <Separator />
+ <div className="flex justify-center items-center gap-x-2">
+ {org?.plan.id === 'free' && (
+ <UpgradePlanButton plan="Pro" source="code-redeem" slug={org.slug}>
+ Upgrade organization
+ </UpgradePlanButton>
+ )}
+ <Button asChild type="default">
+ <Link href={`/org/${org?.slug}`}>Go to organization</Link>
</Button>
</div>
- )}
+ </div>
</div>
) : (
<>
@@ -282,10 +265,10 @@ export const CreditCodeRedemption = ({
control={form.control}
name="code"
render={({ field }) => (
- <FormItemLayout label="Code" className="gap-1">
+ <FormItemLayout label="Code" className="gap-1" layout="horizontal">
<Input_Shadcn_
{...field}
- className="uppercase"
+ className="uppercase w-56 ml-auto"
placeholder="ABCD-1234-EFGH-5678"
/>
</FormItemLayout>
@@ -293,35 +276,34 @@ export const CreditCodeRedemption = ({
/>
{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 className="flex w-full justify-between items-center">
+ <span className="text-sm">Current Balance</span>
+ <div className="flex items-center gap-x-1">
+ <p className="opacity-50 text-sm">$</p>
+ <p className="text-2xl">{customerProfile.balance / -100}</p>
+ <p className="opacity-50 text-sm">/credits</p>
</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>
+ <Admonition type="note" title="Potential future charges">
+ <p>
+ Credits are applied to <strong>{org?.name}</strong> only and cannot be
+ shared or transferred to other organizations. Credits are automatically used
+ toward invoices.
+ </p>
+ <p className="mt-2">
+ When credits run out on a paid plan, your default payment method will be
+ charged—your plan won't be downgraded automatically.
+ </p>
+ </Admonition>
{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_>
+ <Admonition
+ type="warning"
+ title="Unable to redeem code"
+ description={errorRedeemingCode?.message}
+ />
)}
</DialogSection>
diff --git a/apps/studio/components/interfaces/Organization/OrganizationCard.tsx b/apps/studio/components/interfaces/Organization/OrganizationCard.tsx
index a1e8abe1232..3e081c81ac3 100644
--- a/apps/studio/components/interfaces/Organization/OrganizationCard.tsx
+++ b/apps/studio/components/interfaces/Organization/OrganizationCard.tsx
@@ -12,11 +12,13 @@ export const OrganizationCard = ({
href,
isLink = true,
className,
+ onClick,
}: {
organization: Organization
href?: string
isLink?: boolean
className?: string
+ onClick?: () => void
}) => {
const isUserMFAEnabled = useIsMFAEnabled()
const { data } = useOrgProjectsInfiniteQuery({ slug: organization.slug })
@@ -32,6 +34,7 @@ export const OrganizationCard = ({
)}
icon={<Boxes size={18} strokeWidth={1} className="text-foreground" />}
title={organization.name}
+ onClick={onClick}
description={
<div className="flex items-center justify-between text-xs text-foreground-light font-sans">
<div className="flex items-center gap-x-1.5">
diff --git a/apps/studio/components/ui/RequestUpgradeToBillingOwners.tsx b/apps/studio/components/ui/RequestUpgradeToBillingOwners.tsx
index 32e302cc630..5b4bf6735d5 100644
--- a/apps/studio/components/ui/RequestUpgradeToBillingOwners.tsx
+++ b/apps/studio/components/ui/RequestUpgradeToBillingOwners.tsx
@@ -1,9 +1,4 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import { PropsWithChildren, useState } from 'react'
-import { SubmitHandler, useForm } from 'react-hook-form'
-import { toast } from 'sonner'
-import z from 'zod'
-
import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'
import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'
import {
@@ -13,6 +8,9 @@ import {
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useTrack } from 'lib/telemetry/track'
+import { PropsWithChildren, useState } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import { toast } from 'sonner'
import {
Badge,
Button,
@@ -34,6 +32,7 @@ import {
TooltipTrigger,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import z from 'zod'
const FormSchema = z.object({
note: z.string().optional(),
diff --git a/apps/studio/components/ui/UpgradePlanButton.tsx b/apps/studio/components/ui/UpgradePlanButton.tsx
index 7c9851d2b5e..186feac161e 100644
--- a/apps/studio/components/ui/UpgradePlanButton.tsx
+++ b/apps/studio/components/ui/UpgradePlanButton.tsx
@@ -1,13 +1,13 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import Link from 'next/link'
-import { PropsWithChildren } from 'react'
-
import { useFlag, useParams } from 'common'
import { SupportLink } from 'components/interfaces/Support/SupportLink'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import Link from 'next/link'
+import { PropsWithChildren } from 'react'
import { Button } from 'ui'
+
import { ButtonTooltip } from './ButtonTooltip'
import { RequestUpgradeToBillingOwners } from './RequestUpgradeToBillingOwners'
@@ -24,6 +24,7 @@ interface UpgradePlanButtonProps {
featureProposition?: string
disabled?: boolean
className?: string
+ slug?: string
}
/**
@@ -40,18 +41,21 @@ export const UpgradePlanButton = ({
disabled,
children,
className,
+ slug: slugParam,
}: PropsWithChildren<UpgradePlanButtonProps>) => {
const { ref } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const isFreePlan = organization?.plan?.id === 'free'
- const slug = organization?.slug ?? '_'
+ const slug = slugParam ?? organization?.slug ?? '_'
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const { billingAll } = useIsFeatureEnabled(['billing:all'])
const { can: canUpdateSubscription } = useAsyncCheckPermissions(
PermissionAction.BILLING_WRITE,
- 'stripe.subscriptions'
+ 'stripe.subscriptions',
+ undefined,
+ { organizationSlug: slug }
)
const subject = `Enquiry to upgrade ${!!plan ? `to ${plan} ` : ''}plan for organization`
diff --git a/apps/studio/data/organizations/organization-credit-code-redemption-mutation.ts b/apps/studio/data/organizations/organization-credit-code-redemption-mutation.ts
index d8ece7ba77c..daf36dd9e8b 100644
--- a/apps/studio/data/organizations/organization-credit-code-redemption-mutation.ts
+++ b/apps/studio/data/organizations/organization-credit-code-redemption-mutation.ts
@@ -60,10 +60,13 @@ export const useOrganizationCreditCodeRedemptionMutation = ({
return useMutation<RedeemCodeData, ResponseError, OrganizationCreditCodeRedemptionVariables>({
mutationFn: (vars) => redeemCode(vars),
async onSuccess(data, variables, context) {
- const { slug, code } = variables
+ const { slug } = variables
+
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: organizationKeys.customerProfile(slug) }),
+ queryClient.invalidateQueries({ queryKey: subscriptionKeys.orgSubscription(slug) }),
+ ])
- await queryClient.invalidateQueries({ queryKey: organizationKeys.customerProfile(slug) })
- await queryClient.invalidateQueries({ queryKey: subscriptionKeys.orgSubscription(slug) })
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
diff --git a/apps/studio/pages/redeem.tsx b/apps/studio/pages/redeem.tsx
index 4518951f057..39156310bdf 100644
--- a/apps/studio/pages/redeem.tsx
+++ b/apps/studio/pages/redeem.tsx
@@ -1,7 +1,8 @@
+import { useFlag } from 'common'
import Link from 'next/link'
import { useState } from 'react'
-import { Button, Loading } from 'ui'
-import { ShimmeringLoader } from 'ui-patterns'
+import { Button } from 'ui'
+import { Admonition, ShimmeringLoader } from 'ui-patterns'
import { CreditCodeRedemption } from '@/components/interfaces/Organization/BillingSettings/CreditCodeRedemption'
import { OrganizationCard } from '@/components/interfaces/Organization/OrganizationCard'
@@ -12,67 +13,85 @@ import {
ScaffoldHeader,
ScaffoldTitle,
} from '@/components/layouts/Scaffold'
+import AlertError from '@/components/ui/AlertError'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import type { NextPageWithLayout } from '@/types'
const RedeemCreditsContent = () => {
+ const redeemCodeEnabled = useFlag('redeemCodeEnabled')
+ const [selectedOrg, setSelectedOrg] = useState<string | null>(null)
+
const {
data: organizations,
- isLoading: areOrganizationsLoading,
- isFetched: isOrganizationsFetched,
- isSuccess: wasOrganizationsRequestSuccessful,
+ error: errorOrganizations,
+ isLoading: isLoadingOrganizations,
+ isError: isErrorOrganizations,
} = useOrganizationsQuery()
- const [selectedOrg, setSelectedOrg] = useState<string | null>(null)
-
- if (!isOrganizationsFetched) {
+ if (isLoadingOrganizations) {
return (
- <Loading active={areOrganizationsLoading}>
- <div className="grid md:grid-cols-2 pt-10 gap-8">
- <ShimmeringLoader className="w-full" />
-
- <div className="space-y-4">
- <ShimmeringLoader className="w-full h-14" />
- <ShimmeringLoader className="w-full h-14" />
- </div>
+ <div className="grid md:grid-cols-2 pt-10 gap-8">
+ <ShimmeringLoader className="w-full" />
+ <div className="space-y-4">
+ <ShimmeringLoader className="w-full h-14" />
+ <ShimmeringLoader className="w-full h-14" />
</div>
- </Loading>
+ </div>
)
}
- if (!wasOrganizationsRequestSuccessful) {
- return <p className="mt-4">Error loading redeem credit page. Try again later.</p>
+ if (isErrorOrganizations) {
+ return (
+ <AlertError
+ className="mt-4"
+ error={errorOrganizations}
+ subject="Failed to retrieve organizations"
+ />
+ )
}
return (
<div className="grid md:grid-cols-2 pt-10 gap-8">
- <div>
- <p>
- To redeem your credits, select one of your organizations. The credits will be applied to
- that organization only and cannot be transferred or shared between organizations.
- </p>
- <p className="mt-8">
- <span className="font-bold text-foreground-light">Want to start fresh?</span> Create a new
- organization first. You will have to revisit this link after creating the organization to
- redeem the code.
- </p>
- <Button asChild className="mt-4" size="tiny" type="primary">
- <Link href={`/new`}>Create organization</Link>
- </Button>
+ <div className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-1">
+ <p>To redeem your credits, select one of your organizations.</p>
+ <p className="text-sm text-foreground-light text-balance">
+ The credits will be applied to that organization only and cannot be transferred or
+ shared between organizations.
+ </p>
+ </div>
+
+ <div>
+ <p>Want to start fresh?</p>
+ <p className="mt-1 text-sm text-foreground-light text-balance">
+ Create a new organization first. You will have to revisit this link after creating the
+ organization to redeem the code.
+ </p>
+ <Button asChild className="mt-4 w-min" size="tiny" type="primary">
+ <Link href="/new">Create organization</Link>
+ </Button>
+ </div>
</div>
- <div className="space-y-2">
- {organizations?.map((org) => (
- <div key={org.id} onClickCapture={() => setSelectedOrg(org.slug)}>
- <OrganizationCard isLink={false} organization={org} />
- </div>
- ))}
+ <div className="flex flex-col gap-y-2">
+ {redeemCodeEnabled ? (
+ organizations?.map((org) => (
+ <OrganizationCard
+ key={org.id}
+ isLink={false}
+ organization={org}
+ onClick={() => setSelectedOrg(org.slug)}
+ />
+ ))
+ ) : (
+ <Admonition type="note" title="Code redemption coming soon" />
+ )}
</div>
{selectedOrg && (
<CreditCodeRedemption
+ modalVisible
slug={selectedOrg}
- modalVisible={true}
onClose={() => setSelectedOrg(null)}
/>
)}