mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Part 5 of a 6-PR stack migrating all `next/link` imports in `apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known external URLs) and removing `compat/next/link.tsx`. | Part | PR | Scope | | --- | --- | --- | | 1 | #54304 | `data/prefetchers/PrefetchableLink.tsx` and `components/ui/**` | | 2 | #54305 | `components/layouts/**` and top-level shell components | | 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor, BranchManagement, Branching, Functions, Realtime | | 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues, Linter, Reports, QueryPerformance, QuerySources, ConfigDrift, DiskManagement, Compute | | **5** | **#54308 ← this PR** | **Remaining `components/interfaces/**` (Org, Billing, Auth, Support, Home, SignIn, ConnectSheet, etc.)** | | 6 | #54309 | Remove `compat/next/link.tsx` shim, Vite alias, and update basePath tests/docs | Migrates the remaining `components/interfaces/**` directories off `next/link`, leaving zero `next/link` component imports in `apps/studio`. **Changed:** - Replaced `next/link` across all 73 remaining interface files (`Organization`, `OrganizationInvite`, `Billing`, `Auth`, `Support`, `ProjectHome`, `Home`, `Project`, `ProjectCreation`, `ProjectAPIDocs`, `ApiAuthorization`, `App`, `ConnectSheet`, `SignIn`, `APIKeys`, `Account`, `CliLogin`, `Docs`, `JwtSecrets`, `Platform`) - Converted the sole remaining `UrlObject` link (`<Link href={{ pathname: '/sign-in-sso', query }}>`) in `SignInSSOForm.tsx` to `<Link to="/sign-in-sso" search={query}>` - Migrated `SupportLink.tsx` onto `DynamicLink` (`createSupportFormUrl(...)`) - Standardized external `target="_blank"` anchors with `rel="noreferrer noopener"`, switched `OverviewMetrics.tsx` observability link to typed `<Link to="/project/$ref/observability/auth">`, and adopted `InlineLink` / `InlineLinkClassName` on inline paragraph links per review feedback Addresses [FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link) ## To test - [ ] Check Organization (billing, usage, team, documents, AWS Marketplace), Auth (providers, templates, rate limits, users, OAuth apps), Support form/links, Project Home, Connect sheet, and Sign-In/SSO links - [ ] Verify `SignInWithSSOButton` preserves query params when navigating to `/sign-in-sso` - [ ] Verify `SupportLink` pre-populates support form query parameters cleanly --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
381 lines
13 KiB
TypeScript
381 lines
13 KiB
TypeScript
import HCaptcha from '@hcaptcha/react-hcaptcha'
|
|
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { Link, useLocation } from '@tanstack/react-router'
|
|
import { CalendarIcon, InfoIcon, PartyPopperIcon } from 'lucide-react'
|
|
import { useEffect, useRef, useState } from 'react'
|
|
import { SubmitHandler, useForm } from 'react-hook-form'
|
|
import {
|
|
Button,
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogSection,
|
|
DialogSectionSeparator,
|
|
DialogTitle,
|
|
DialogTrigger,
|
|
Form,
|
|
FormField,
|
|
Input,
|
|
Separator,
|
|
} from 'ui'
|
|
import { Admonition } from 'ui-patterns/Admonition'
|
|
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
|
|
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
|
|
import { TimestampInfo } from 'ui-patterns/TimestampInfo'
|
|
import { z } from 'zod'
|
|
|
|
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
|
import { UpgradePlanButton } from '@/components/ui/UpgradePlanButton'
|
|
import { useOrganizationCreditCodeRedemptionMutation } from '@/data/organizations/organization-credit-code-redemption-mutation'
|
|
import { useOrganizationQuery } from '@/data/organizations/organization-query'
|
|
import { useOrgBalanceQuery } from '@/data/subscriptions/org-balance-query'
|
|
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
|
|
import { useLatest } from '@/hooks/misc/useLatest'
|
|
|
|
const FORM_ID = 'credit-code-redemption'
|
|
|
|
const FormSchema = z.object({
|
|
code: z.string().min(1, 'Code is required'),
|
|
})
|
|
|
|
type CreditCodeRedemptionForm = z.infer<typeof FormSchema>
|
|
|
|
export const CreditCodeRedemption = ({
|
|
slug,
|
|
modalVisible = false,
|
|
onClose,
|
|
}: {
|
|
slug?: string
|
|
modalVisible?: boolean
|
|
onClose?: () => void
|
|
}) => {
|
|
const pathname = useLocation({ select: (location) => location.pathname })
|
|
const codeFromParams = useLocation({
|
|
select: (location) => {
|
|
const queryCode = (location.search as Record<string, string | string[] | undefined>).code
|
|
return Array.isArray(queryCode) ? queryCode[0] : queryCode
|
|
},
|
|
})
|
|
const [codeRedemptionModalVisible, setCodeRedemptionModalVisible] = useState(
|
|
modalVisible || false
|
|
)
|
|
|
|
const { data: org, isLoading: isOrgLoading } = useOrganizationQuery({ slug })
|
|
const { data: orgBalance, isLoading: isOrgBalanceLoading } = useOrgBalanceQuery(
|
|
{ orgSlug: slug },
|
|
{ enabled: codeRedemptionModalVisible }
|
|
)
|
|
const combinedCreditBalanceCents = orgBalance?.total_balance_cents
|
|
|
|
const { can: canRedeemCode, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissionsV2(
|
|
FGA_PERMISSIONS.ORGANIZATION.BILLING_WRITE,
|
|
{ organizationSlug: slug }
|
|
)
|
|
|
|
const captchaRef = useRef<HCaptcha>(null)
|
|
const captchaTokenRef = useRef<string | null>(null)
|
|
const codeRedemptionDisabled =
|
|
!canRedeemCode || !isPermissionsLoaded || isOrgLoading || isOrgBalanceLoading
|
|
|
|
const form = useForm<CreditCodeRedemptionForm>({
|
|
resolver: zodResolver(FormSchema),
|
|
defaultValues: { code: '' },
|
|
})
|
|
const { isValid } = form.formState
|
|
|
|
const {
|
|
mutate: redeemCode,
|
|
isPending: redeemingCode,
|
|
error: errorRedeemingCode,
|
|
data: codeRedemptionResult,
|
|
reset: resetCodeRedemption,
|
|
} = useOrganizationCreditCodeRedemptionMutation({
|
|
onSuccess: () => {
|
|
form.setValue('code', '')
|
|
resetCaptcha()
|
|
},
|
|
})
|
|
|
|
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)
|
|
|
|
const onSubmit: SubmitHandler<CreditCodeRedemptionForm> = async ({ code }) => {
|
|
const token = await initHcaptcha()
|
|
redeemCode({ slug, code, hcaptchaToken: token })
|
|
}
|
|
|
|
const onCodeRedemptionDialogVisibilityChange = (visible: boolean) => {
|
|
setCodeRedemptionModalVisible(visible)
|
|
if (!visible) {
|
|
resetCodeRedemption()
|
|
resetCaptcha()
|
|
onClose?.()
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (typeof codeFromParams === 'string' && codeFromParams.trim().length > 2) {
|
|
form.setValue('code', codeFromParams)
|
|
}
|
|
}, [codeFromParams, form])
|
|
|
|
useEffect(() => {
|
|
if (codeRedemptionModalVisible) {
|
|
initHcaptchaRef.current()
|
|
}
|
|
}, [codeRedemptionModalVisible, initHcaptchaRef])
|
|
|
|
function getRedemptionNotice() {
|
|
const redemptionIsReady = !!codeRedemptionResult
|
|
if (!redemptionIsReady) {
|
|
return undefined
|
|
}
|
|
|
|
const alreadyRedeemedCents = codeRedemptionResult.already_redeemed_partner_credits ?? 0
|
|
if (!alreadyRedeemedCents) {
|
|
return undefined
|
|
}
|
|
|
|
return `Since you already redeemed $${alreadyRedeemedCents / 100} through other deals, we couldn't grant the full $${((alreadyRedeemedCents + codeRedemptionResult.amount_cents) / 100).toFixed(0)}.`
|
|
}
|
|
|
|
const redemptionNotice = getRedemptionNotice()
|
|
|
|
return (
|
|
<Dialog open={codeRedemptionModalVisible} onOpenChange={onCodeRedemptionDialogVisibilityChange}>
|
|
{!modalVisible && (
|
|
<DialogTrigger asChild>
|
|
<ButtonTooltip
|
|
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 size="medium" onInteractOutside={(e) => e.preventDefault()}>
|
|
<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
|
|
}}
|
|
/>
|
|
|
|
{/* screen reader */}
|
|
<div role="status" aria-live="polite" className="sr-only">
|
|
{!!codeRedemptionResult && (
|
|
<span>{`$${codeRedemptionResult.amount_cents / 100} credits applied.`}</span>
|
|
)}
|
|
{redemptionNotice && <span>{` ${redemptionNotice}`}</span>}
|
|
</div>
|
|
|
|
{!!codeRedemptionResult ? (
|
|
<div className="p-8">
|
|
<div className="text-center flex items-center justify-center">
|
|
<PartyPopperIcon strokeWidth={1} className="h-14 w-14" />
|
|
</div>
|
|
|
|
<div className="text-center">
|
|
<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">
|
|
<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>
|
|
|
|
{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-8 rounded-lg">
|
|
<CalendarIcon className="h-4 w-4" />
|
|
<span>
|
|
Your credits expire on{' '}
|
|
<TimestampInfo
|
|
className="text-sm"
|
|
utcTimestamp={codeRedemptionResult.credits_expire_at}
|
|
labelFormat="MMMM DD, YYYY"
|
|
/>
|
|
.
|
|
</span>
|
|
</div>
|
|
)}
|
|
|
|
{!!redemptionNotice && (
|
|
<div className="mt-2 flex items-center justify-center gap-2 text-sm text-muted-foreground bg-muted/50 py-3 px-8 rounded-lg">
|
|
<InfoIcon className="h-4 w-4 shrink-0" />
|
|
<span>{redemptionNotice}</span>
|
|
</div>
|
|
)}
|
|
|
|
{(!pathname.includes('/org/') || org?.plan.id === 'free') && (
|
|
<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>
|
|
)}
|
|
|
|
{!pathname.includes('/org/') && (
|
|
<Button asChild>
|
|
<Link to="/org/$slug" params={{ slug: org?.slug ?? '_' }}>
|
|
Go to organization
|
|
</Link>
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
) : (
|
|
<>
|
|
<DialogHeader>
|
|
<DialogTitle>Redeem Code</DialogTitle>
|
|
<DialogDescription className="space-y-2">
|
|
Redeem your credit code to add credits to your organization
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<DialogSectionSeparator />
|
|
|
|
<Form {...form}>
|
|
{isOrgLoading || isOrgBalanceLoading || !isPermissionsLoaded ? (
|
|
<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
|
|
control={form.control}
|
|
name="code"
|
|
render={({ field }) => (
|
|
<FormItemLayout
|
|
hideMessage
|
|
label="Code"
|
|
className="gap-1"
|
|
layout="horizontal"
|
|
>
|
|
<Input
|
|
{...field}
|
|
className="uppercase w-56 ml-auto"
|
|
placeholder="ABCD-1234-EFGH-5678"
|
|
/>
|
|
</FormItemLayout>
|
|
)}
|
|
/>
|
|
|
|
{combinedCreditBalanceCents !== undefined && combinedCreditBalanceCents > 0 && (
|
|
<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">{combinedCreditBalanceCents / 100}</p>
|
|
<p className="opacity-50 text-sm">/credits</p>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<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 && (
|
|
<Admonition
|
|
type="warning"
|
|
title="Unable to redeem code"
|
|
description={errorRedeemingCode?.message}
|
|
/>
|
|
)}
|
|
</DialogSection>
|
|
|
|
<DialogFooter>
|
|
<ButtonTooltip
|
|
variant="primary"
|
|
className="pointer-events-auto"
|
|
loading={redeemingCode}
|
|
disabled={codeRedemptionDisabled || !isValid}
|
|
type="submit"
|
|
tooltip={{
|
|
content: {
|
|
side: 'bottom',
|
|
text:
|
|
isPermissionsLoaded && !canRedeemCode
|
|
? 'You need additional permissions to redeem codes'
|
|
: undefined,
|
|
},
|
|
}}
|
|
>
|
|
Redeem
|
|
</ButtonTooltip>
|
|
</DialogFooter>
|
|
</form>
|
|
)}
|
|
</Form>
|
|
</>
|
|
)}
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|