The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Implement add new payment method flow in billing
Joshen Lim229a8af9be12
diff --git a/studio/components/interfaces/Billing/AddNewPaymentMethodModal.tsx b/studio/components/interfaces/Billing/AddNewPaymentMethodModal.tsxdeleted file mode 100644index adcd8e3d5e7..00000000000--- a/studio/components/interfaces/Billing/AddNewPaymentMethodModal.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { FC } from 'react'-import { Button, Modal } from '@supabase/ui'-import { PaymentElement } from '@stripe/react-stripe-js'--interface Props {- visible: boolean- onCancel: () => void-}--// Add payment method: https://stripe.com/docs/payments/save-and-reuse?platform=web&html-or-react=react--const AddNewPaymentMethodModal: FC<Props> = ({ visible, onCancel }) => {- return (- <Modal- hideFooter- size="medium"- visible={visible}- header="Add new payment method"- onCancel={onCancel}- className="PAYMENT"- >- <div className="py-4 space-y-4">- <Modal.Content>- <PaymentElement />- </Modal.Content>- <Modal.Seperator />- <Modal.Content>- <div className="flex items-center gap-2">- <Button htmlType="button" type="primary" onClick={() => {}} block>- Save- </Button>- <Button htmlType="button" type="default" onClick={onCancel} block>- Cancel- </Button>- </div>- </Modal.Content>- </div>- </Modal>- )-}--export default AddNewPaymentMethodModaldiff --git a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsx b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsxnew file mode 100644index 00000000000..db8b34ac942--- /dev/null+++ b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/AddPaymentMethodForm.tsx@@ -0,0 +1,62 @@+import { FC, useState } from 'react'+import { Button, Modal } from '@supabase/ui'+import { useStripe, useElements, PaymentElement } from '@stripe/react-stripe-js'++import { useStore } from 'hooks'+import { getURL } from 'lib/helpers'++interface Props {+ onCancel: () => void+}++// Stripe docs recommend to use the new SetupIntent flow over+// manually creating and attaching payment methods via the API+// Small UX annoyance here, that the page will be refreshed++const AddPaymentMethodForm: FC<Props> = ({ onCancel }) => {+ const { ui } = useStore()+ const projectRef = ui.selectedProject?.ref ?? ''++ const stripe = useStripe()+ const elements = useElements()++ const [isSaving, setIsSaving] = useState(false)++ const handleSubmit = async (event: any) => {+ event.preventDefault()+ setIsSaving(true)++ if (!stripe || !elements) {+ console.error('Stripe.js has not loaded')+ return+ }++ await stripe.confirmSetup({+ elements,+ confirmParams: {+ return_url: `${getURL()}/project/${projectRef}/settings/billing/update/pro`,+ },+ })+ }++ return (+ <form onSubmit={handleSubmit}>+ <Modal.Content>+ <PaymentElement />+ </Modal.Content>+ <Modal.Seperator />+ <Modal.Content>+ <div className="flex items-center space-x-2 pt-2">+ <Button block htmlType="submit" type="primary" loading={isSaving}>+ Save+ </Button>+ <Button htmlType="button" type="default" onClick={onCancel} block>+ Cancel+ </Button>+ </div>+ </Modal.Content>+ </form>+ )+}++export default AddPaymentMethodFormdiff --git a/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsx b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsxnew file mode 100644index 00000000000..4b2ec5742cc--- /dev/null+++ b/studio/components/interfaces/Billing/AddNewPaymentMethodModal/index.tsx@@ -0,0 +1,67 @@+import { FC, useEffect, useState } from 'react'+import { Button, IconLoader, Modal } from '@supabase/ui'+import { loadStripe } from '@stripe/stripe-js'+import { Elements } from '@stripe/react-stripe-js'++import { useStore } from 'hooks'+import { post } from 'lib/common/fetch'+import { API_URL, STRIPE_PUBLIC_KEY } from 'lib/constants'+import AddPaymentMethodForm from './AddPaymentMethodForm'++interface Props {+ visible: boolean+ onCancel: () => void+}++const stripePromise = loadStripe(STRIPE_PUBLIC_KEY)++const AddNewPaymentMethodModal: FC<Props> = ({ visible, onCancel }) => {+ const { ui } = useStore()+ const [intent, setIntent] = useState<any>()++ useEffect(() => {+ if (visible) {+ onSelectAddNewPaymentMethod()+ }+ }, [visible])++ const onSelectAddNewPaymentMethod = async () => {+ setIntent(undefined)+ const orgSlug = ui.selectedOrganization?.slug ?? ''+ const customerId = ui.selectedOrganization?.stripe_customer_id ?? ''+ const intent = await post(`${API_URL}/organizations/${orgSlug}/payment/setup-intent`, {+ customer_id: customerId,+ })+ setIntent(intent)+ }++ const options = {+ clientSecret: intent ? intent.client_secret : '',+ appearance: { theme: 'night', labels: 'floating' },+ } as any++ return (+ <Modal+ hideFooter+ size="medium"+ visible={visible}+ header="Add new payment method"+ onCancel={onCancel}+ className="PAYMENT"+ >+ <div className="py-4 space-y-4">+ {intent !== undefined ? (+ <Elements stripe={stripePromise} options={options}>+ <AddPaymentMethodForm onCancel={onCancel} />+ </Elements>+ ) : (+ <div className="w-full flex items-center justify-center py-20">+ <IconLoader size={16} className="animate-spin" />+ </div>+ )}+ </div>+ </Modal>+ )+}++export default AddNewPaymentMethodModaldiff --git a/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsx b/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsxindex c4ac0877143..94edd90d1ed 100644--- a/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsx+++ b/studio/components/interfaces/Billing/AddOns/ComputeSizeSelection.tsx@@ -2,8 +2,6 @@ import { FC } from 'react'import { Radio } from '@supabase/ui'import { formatComputeSizes } from './AddOns.utils'-// [TODO] please type the vairables properly-interface Props {computeSizes: any[]selectedComputeSize: anydiff --git a/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx b/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsxindex c05e0baa7a7..9cd20325825 100644--- a/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx+++ b/studio/components/interfaces/Billing/ExitSurvey/ExitSurvey.tsx@@ -103,7 +103,7 @@ const ExitSurvey: FC<Props> = ({ freeTier, onSelectBack }) => {<UpdateSuccessprojectRef={projectRef || ''}title="Your project has been updated"- message={`A total of $${returnedAmount} credits will be refunded on ${billingDate.toLocaleDateString(+ message={`A total of $${returnedAmount} will be refunded as credits on ${billingDate.toLocaleDateString('en-US',{day: 'numeric',diff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsxindex 4435ea63823..83d96fed2af 100644--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsx+++ b/studio/components/interfaces/Billing/PaymentSummaryPanel/CostBreakdownModal.tsx@@ -80,10 +80,23 @@ const CostBreakdownModal: FC<Props> = ({</div>)})}- <div className="flex items-center py-2 px-4">- <div className="text-sm w-[75%]">Total amount</div>- <div className="text-sm w-[10%] text-right"></div>- <div className="text-xl w-[15%] text-right">${totalDue.toFixed(2)}</div>+ <div className="flex flex-col py-2 px-4 space-y-1">+ <div className="flex items-center">+ <div className="text-sm w-[75%]">Total amount</div>+ <div className="text-sm w-[10%] text-right"></div>+ <div className="text-xl w-[15%] text-right">+ ${totalDue < 0 ? 0 : totalDue.toFixed(2)}+ </div>+ </div>+ {totalDue < 0 && (+ <div className="flex items-center text-scale-1100">+ <div className="text-sm w-[75%]">+ Amount returned as credits for unused resources+ </div>+ <div className="text-sm w-[10%] text-right"></div>+ <div className="text-sm w-[15%] text-right">${Math.abs(totalDue).toFixed(2)}</div>+ </div>+ )}</div></div></Modal.Content>diff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsxindex ca6dddd21ee..07e55f10521 100644--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsx+++ b/studio/components/interfaces/Billing/PaymentSummaryPanel/PaymentTotal.tsx@@ -1,27 +1,21 @@import { FC, useState } from 'react'-import { Loading, IconHelpCircle, Modal } from '@supabase/ui'+import { Loading, IconHelpCircle, Button } from '@supabase/ui'+import * as Tooltip from '@radix-ui/react-tooltip'import { SubscriptionPreview } from '../Billing.types'import CostBreakdownModal from './CostBreakdownModal'interface Props {subscriptionPreview?: SubscriptionPreviewisRefreshingPreview: boolean- hasChangesToPlan: booleanisSpendCapEnabled: boolean}const PaymentTotal: FC<Props> = ({subscriptionPreview,isRefreshingPreview,- hasChangesToPlan,isSpendCapEnabled,}) => {const hasChanges = subscriptionPreview?.has_changes ?? false- const hasCreditsBalance = (subscriptionPreview?.available_credit_balance ?? 0) > 0- const availableCreditBalance = (subscriptionPreview?.available_credit_balance ?? 0) / 100- const returnedCredits = (subscriptionPreview?.returned_credits_for_unused_time ?? 0) / 100- const remainingCreditBalance = (subscriptionPreview?.remaining_credit_balance ?? 0) / 100-const totalMonthlyCost = (subscriptionPreview?.base_amount_due_next_billing_cycle ?? 0) / 100const amountDueImmediately = (subscriptionPreview?.amount_due_immediately ?? 0) / 100const billingDate = new Date((subscriptionPreview?.bill_on ?? 0) * 1000)@@ -41,26 +35,6 @@ const PaymentTotal: FC<Props> = ({return (<>- {/* Credit balance details (If available) */}- {/* {hasCreditsBalance && (- <>- <Loading active={isRefreshingPreview}>- <div className="space-y-2">- <div className="flex items-start justify-between space-x-20">- <div>- <p className="text-sm">Available credit balance</p>- <p className="text-sm text-scale-1100">- Including credits returned for unused time from this change- </p>- </div>- <p className="text-sm">${availableCreditBalance.toFixed(2)}</p>- </div>- </div>- </Loading>- <div className="h-px w-full bg-scale-600" />- </>- )} */}-{/* Payment total */}<Loading active={isRefreshingPreview}><div className="mb-2 space-y-4">@@ -68,29 +42,58 @@ const PaymentTotal: FC<Props> = ({<div className=""><div className="flex items-center space-x-2"><p>Total amount due</p>- {hasChangesToPlan && (- <IconHelpCircle- size={16}- strokeWidth={1.5}- className="cursor-pointer opacity-50 hover:opacity-100 transition"- onClick={() => setShowCostBreakdown(true)}- />+ {hasChanges && (+ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger>+ <IconHelpCircle+ size={16}+ strokeWidth={1.5}+ className="cursor-pointer opacity-50 hover:opacity-100 transition"+ onClick={() => setShowCostBreakdown(true)}+ />+ </Tooltip.Trigger>+ <Tooltip.Content side="bottom">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'bg-scale-100 shadow py-1 px-2 rounded leading-none', // background+ 'border border-scale-200 ', //border+ ].join(' ')}+ >+ <span className="text-scale-1200 text-xs">How is this calculated?</span>+ </div>+ </Tooltip.Content>+ </Tooltip.Root>)}</div>{hasChanges ? (<div className="space-y-2">- <p className="text-sm text-scale-1100">- This amount {!isSpendCapEnabled && !isBillingToday && '+ usage fees '}will be- charged on{' '}- <span className="text-scale-1200">- {billingDate.toLocaleDateString('en-US', {- day: 'numeric',- month: 'long',- year: 'numeric',- })}- </span>- .- </p>+ {amountDueImmediately < 0 ? (+ <p className="text-sm text-scale-1100">+ A total of ${Math.abs(amountDueImmediately).toFixed(2)} will be returned on{' '}+ <span className="font-bold text-green-1100">+ {billingDate.toLocaleDateString('en-US', {+ day: 'numeric',+ month: 'long',+ year: 'numeric',+ })}+ </span>{' '}+ for unused resources.+ </p>+ ) : (+ <p className="text-sm text-scale-1100">+ This amount {!isSpendCapEnabled && !isBillingToday && '+ usage fees '}will be+ charged on{' '}+ <span className="font-bold text-green-1100">+ {billingDate.toLocaleDateString('en-US', {+ day: 'numeric',+ month: 'long',+ year: 'numeric',+ })}+ </span>+ .+ </p>+ )}<p className="text-sm text-scale-1100">You'll pay a monthly total of{' '}<span className="text-scale-1200">@@ -106,18 +109,12 @@ const PaymentTotal: FC<Props> = ({<div className="flex justify-end items-end relative -top-[8px]"><p className="text-scale-1100 relative -top-[1px]">$</p><p className="text-2xl">- {!hasChangesToPlan+ {!hasChanges? '0.00': (amountDueImmediately < 0 ? 0 : amountDueImmediately).toFixed(2)}</p></div></div>- {/* {hasCreditsBalance && (- <div className="flex items-start justify-between">- <p className="text-sm">Remaining credit balance</p>- <p className="text-sm">${remainingCreditBalance.toFixed(2)}</p>- </div>- )} */}</div></Loading>diff --git a/studio/components/interfaces/Billing/PaymentSummaryPanel/index.tsx b/studio/components/interfaces/Billing/PaymentSummaryPanel/index.tsxindex 0ebfcb2d373..ab517c8aadc 100644--- a/studio/components/interfaces/Billing/PaymentSummaryPanel/index.tsx+++ b/studio/components/interfaces/Billing/PaymentSummaryPanel/index.tsx@@ -1,10 +1,11 @@import { FC } from 'react'-import { Listbox, IconLoader, Button, IconPlus } from '@supabase/ui'+import { Listbox, IconLoader, Button, IconPlus, IconAlertCircle } from '@supabase/ui'import { STRIPE_PRODUCT_IDS } from 'lib/constants'import { StripeProduct } from '..'import { SubscriptionPreview } from '../Billing.types'import PaymentTotal from './PaymentTotal'+import InformationBox from 'components/ui/InformationBox'interface Props {isRefreshingPreview: boolean@@ -110,6 +111,17 @@ const PaymentSummaryPanel: FC<Props> = ({</p></div>)}+ {isChangingComputeSize && (+ <div className="!mt-4">+ <InformationBox+ hideCollapse+ defaultVisibility+ icon={<IconAlertCircle strokeWidth={2} />}+ title="Changing your compute size"+ description="It will take up to 2 minutes for changes to take place, and your project will be unavailable during that time"+ />+ </div>+ )}</div><div className="h-px w-full bg-scale-600" />@@ -117,13 +129,12 @@ const PaymentSummaryPanel: FC<Props> = ({<PaymentTotalsubscriptionPreview={subscriptionPreview}isRefreshingPreview={isRefreshingPreview}- hasChangesToPlan={hasChangesToPlan}isSpendCapEnabled={isSpendCapEnabled}/>{/* Payment method selection */}<div className="space-y-2">- <p>Select payment method</p>+ <p className="text-sm">Select payment method</p>{isLoadingPaymentMethods ? (<div className="flex items-center rounded-md space-x-4 px-4 py-2 bg-scale-400 border border-scale-700"><IconLoader className="animate-spin" size={14} />diff --git a/studio/components/interfaces/Billing/ProUpgrade.tsx b/studio/components/interfaces/Billing/ProUpgrade/ProUpgrade.tsxsimilarity index 56%rename from studio/components/interfaces/Billing/ProUpgrade.tsxrename to studio/components/interfaces/Billing/ProUpgrade/ProUpgrade.tsxindex 164d859021d..d978e3d76c5 100644--- a/studio/components/interfaces/Billing/ProUpgrade.tsx+++ b/studio/components/interfaces/Billing/ProUpgrade/ProUpgrade.tsx@@ -4,7 +4,7 @@ import { useRouter } from 'next/router'import { Badge, Button, IconArrowLeft, IconHelpCircle, Toggle, Modal } from '@supabase/ui'import { useStore } from 'hooks'-import { getURL, timeout } from 'lib/helpers'+import { getURL } from 'lib/helpers'import { post, patch } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import Divider from 'components/ui/Divider'@@ -13,35 +13,31 @@ import {ComputeSizeSelection,StripeSubscription,AddNewPaymentMethodModal,-} from '.'-import { BillingPlan } from './PlanSelection/Plans/Plans.types'+} from '..'import { STRIPE_PRODUCT_IDS } from 'lib/constants'-import { SubscriptionPreview } from './Billing.types'+import { SubscriptionPreview } from '../Billing.types'+import UpdateSuccess from '../UpdateSuccess'+import { formSubscriptionUpdatePayload } from './ProUpgrade.utils'interface Props {- visible: booleanproducts: { tiers: any[]; addons: any[] }-- currentSubscription: StripeSubscription- selectedPlan?: BillingPlanpaymentMethods?: any[]+ currentSubscription: StripeSubscriptionisLoadingPaymentMethods: booleanonSelectBack: () => void}const ProUpgrade: FC<Props> = ({- visible,products,- currentSubscription,- selectedPlan,paymentMethods,+ currentSubscription,isLoadingPaymentMethods,onSelectBack,}) => {const { ui } = useStore()const router = useRouter()- const { tiers, addons } = products+ const { addons } = productsconst projectRef = ui.selectedProject?.refconst currentComputeSize =@@ -67,24 +63,20 @@ const ProUpgrade: FC<Props> = ({const [selectedComputeSize, setSelectedComputeSize] = useState<any>(currentComputeSize)const [subscriptionPreview, setSubscriptionPreview] = useState<SubscriptionPreview>()+ const selectedTier = isSpendCapEnabled+ ? products?.tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PRO)+ : products?.tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PAYG)+useEffect(() => {if (!isLoadingPaymentMethods && paymentMethods && paymentMethods.length > 0) {// [TODO] Figure out how to get the DEFAULT payment method- setSelectedPaymentMethod(paymentMethods[0])+ setSelectedPaymentMethod(paymentMethods[0].id)}}, [isLoadingPaymentMethods, paymentMethods])useEffect(() => {- if (selectedPlan !== undefined && selectedPlan.id !== STRIPE_PRODUCT_IDS.FREE) {- getSubscriptionPreview()- }- }, [selectedPlan, selectedComputeSize, isSpendCapEnabled])-- useEffect(() => {- if (selectedPlan?.id === STRIPE_PRODUCT_IDS.PRO) {- setIsSpendCapEnabled(true)- }- }, [selectedPlan])+ getSubscriptionPreview()+ }, [selectedComputeSize, isSpendCapEnabled])const onSelectComputeSizeOption = (option: any) => {setSelectedComputeSize(option)@@ -106,25 +98,16 @@ const ProUpgrade: FC<Props> = ({}const getSubscriptionPreview = async () => {- const selectedTier = !isSpendCapEnabled- ? tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PAYG)- : tiers.find((tier: any) => tier.id === selectedPlan?.id)-- // [TODO] Small currently has no stripe product attached, so FE has a hardcoded ID just for that product- // [UPDATE] it now has, just verify if attaching a Small will mess things up- const addons = selectedComputeSize.name.includes('[Small]')- ? []- : [selectedComputeSize.prices[0].id]- const proration_date = Math.floor(Date.now() / 1000)-if (!selectedTier) return+ const payload = formSubscriptionUpdatePayload(+ selectedTier,+ selectedComputeSize,+ selectedPaymentMethod+ )+setIsRefreshingPreview(true)- const preview = await post(`${API_URL}/projects/${projectRef}/subscription/preview`, {- tier: selectedTier.prices[0].id,- addons,- proration_date,- })+ const preview = await post(`${API_URL}/projects/${projectRef}/subscription/preview`, payload)if (preview.error) {ui.setNotification({category: 'error',@@ -133,29 +116,18 @@ const ProUpgrade: FC<Props> = ({}setSubscriptionPreview(preview)setIsRefreshingPreview(false)- console.log('Preview retrieved', preview)}// Exact same thing as getSubscriptionpreview, can we make them into oneconst onConfirmPayment = async () => {- const selectedTier = !isSpendCapEnabled- ? tiers.find((tier: any) => tier.id === STRIPE_PRODUCT_IDS.PAYG)- : tiers.find((tier: any) => tier.id === selectedPlan?.id)-- // [TODO] Small currently has no stripe product attached, so FE has a hardcoded ID just for that product- // [UPDATE] it now has, just verify if attaching a Small will mess things up- const addons = selectedComputeSize.name.includes('[Small]')- ? []- : [selectedComputeSize.prices[0].id]- const proration_date = Math.floor(Date.now() / 1000)+ const payload = formSubscriptionUpdatePayload(+ selectedTier,+ selectedComputeSize,+ selectedPaymentMethod+ )setIsSubmitting(true)- await timeout(1000)- const res = await patch(`${API_URL}/projects/${projectRef}/subscription`, {- tier: selectedTier.prices[0].id,- addons,- proration_date,- })+ const res = await patch(`${API_URL}/projects/${projectRef}/subscription`, payload)if (res?.error) {ui.setNotification({category: 'error',@@ -163,120 +135,120 @@ const ProUpgrade: FC<Props> = ({})} else {setIsSuccessful(true)- ui.setNotification({- category: 'success',- message: 'Done',- })- console.log('Succesfully updated subscription')}setIsSubmitting(false)}if (!isSubmitting && isSuccessful) {- return <div className="">Some success state here to be done</div>+ return (+ <UpdateSuccess+ projectRef={projectRef || ''}+ title="Your project has been updated!"+ message="Let us know if you have any feedback at [email protected]."+ />+ )}return (<><Transition- show={visible}+ showenter="transition ease-out duration-300"enterFrom="transform opacity-0 translate-x-10"enterTo="transform opacity-100 translate-x-0"className="w-full flex items-start justify-between">- {visible && (- <>- <div className="space-y-8 w-3/5">- <div className="relative ml-64">- <div className="absolute top-[2px] -left-24">- <Button type="text" icon={<IconArrowLeft />} onClick={onSelectBack}>- Back- </Button>- </div>- <div className="space-y-8">- <h4 className="text-lg">Change your project's subscription</h4>- <div- className="space-y-8 overflow-scroll pb-8 pr-20"- style={{ height: 'calc(100vh - 6.3rem - 49.5px)' }}- >- {!isManagingProSubscription ? (- <div className="space-y-1">- <h3 className="text-xl">- Welcome to <span className="text-green-1100">Pro</span>- <p className="text-sm text-scale-1100">- Your new subscription will begin immediately after payment- </p>- </h3>- </div>- ) : (- <div className="space-y-1">- <h3 className="text-xl">- Managing your <span className="text-green-1100">Pro</span> plan- <p className="text-sm text-scale-1100">- Your billing cycle will reset after payment- </p>- </h3>- </div>- )}- <div className="flex items-start justify-between">- <div>- <div className="flex items-center space-x-2">- <p>Enable spend cap</p>- <IconHelpCircle- size={16}- strokeWidth={1.5}- className="cursor-pointer opacity-50 hover:opacity-100 transition"- onClick={() => setShowSpendCapHelperModal(true)}- />- </div>+ <>+ <div className="w-3/5 mt-10">+ <div className="relative ml-64">+ <div className="absolute top-[2px] -left-24">+ <Button type="text" icon={<IconArrowLeft />} onClick={onSelectBack}>+ Back+ </Button>+ </div>+ <div className="space-y-8">+ <h4 className="text-lg">Change your project's subscription</h4>+ <div+ className="space-y-8 overflow-scroll pb-8 pr-20"+ style={{ height: 'calc(100vh - 6.3rem - 49.5px)' }}+ >+ {!isManagingProSubscription ? (+ <div className="space-y-1">+ <h3 className="text-xl">+ Welcome to <span className="text-green-1100">Pro</span><p className="text-sm text-scale-1100">- If disabled, additional resources will be charged on a per-usage basis+ Your new subscription will begin immediately after payment</p>- </div>- <Toggle- checked={isSpendCapEnabled}- onChange={() => setIsSpendCapEnabled(!isSpendCapEnabled)}- />+ </h3></div>- <Divider light />- <div className="flex items-center space-x-2">- <h4 className="text-lg">Extend your project with add-ons</h4>- <Badge color="green">Optional</Badge>+ ) : (+ <div className="space-y-1">+ <h3 className="text-xl">+ Managing your <span className="text-green-1100">Pro</span> plan+ <p className="text-sm text-scale-1100">+ Your billing cycle will reset after payment+ </p>+ </h3></div>- <ComputeSizeSelection- computeSizes={addons || []}- selectedComputeSize={selectedComputeSize}- onSelectOption={onSelectComputeSizeOption}+ )}+ <div className="flex items-start justify-between">+ <div>+ <div className="flex items-center space-x-2">+ <p>Enable spend cap</p>+ <IconHelpCircle+ size={16}+ strokeWidth={1.5}+ className="cursor-pointer opacity-50 hover:opacity-100 transition"+ onClick={() => setShowSpendCapHelperModal(true)}+ />+ </div>+ <p className="text-sm text-scale-1100">+ If disabled, additional resources will be charged on a per-usage basis+ </p>+ </div>+ <Toggle+ checked={isSpendCapEnabled}+ onChange={() => setIsSpendCapEnabled(!isSpendCapEnabled)}/></div>+ <Divider light />+ <div className="flex items-center space-x-2">+ <h4 className="text-lg">Extend your project with add-ons</h4>+ <Badge color="green">Optional</Badge>+ </div>+ <ComputeSizeSelection+ computeSizes={addons || []}+ selectedComputeSize={selectedComputeSize}+ onSelectOption={onSelectComputeSizeOption}+ /></div></div></div>- <div className="w-2/5 -mt-10">- <PaymentSummaryPanel- isRefreshingPreview={isRefreshingPreview}- subscriptionPreview={subscriptionPreview}- currentPlan={currentSubscription.tier}- selectedPlan={selectedPlan}- isSpendCapEnabled={isSpendCapEnabled}- currentComputeSize={currentComputeSize}- selectedComputeSize={selectedComputeSize}- paymentMethods={paymentMethods}- isLoadingPaymentMethods={isLoadingPaymentMethods}- selectedPaymentMethod={selectedPaymentMethod}- onSelectPaymentMethod={setSelectedPaymentMethod}- onSelectAddNewPaymentMethod={() => {- // [TODO] For now, use stripe's web portal to add payment method- redirectToPortal('/payment-methods')- // setShowAddPaymentMethodModal(true)- }}- onConfirmPayment={onConfirmPayment}- isSubmitting={isSubmitting}- />- </div>- </>- )}+ </div>+ <div className="w-2/5">+ <PaymentSummaryPanel+ isRefreshingPreview={isRefreshingPreview}+ subscriptionPreview={subscriptionPreview}+ currentPlan={currentSubscription.tier}+ selectedPlan={selectedTier}+ isSpendCapEnabled={isSpendCapEnabled}+ currentComputeSize={currentComputeSize}+ selectedComputeSize={selectedComputeSize}+ paymentMethods={paymentMethods}+ isLoadingPaymentMethods={isLoadingPaymentMethods}+ selectedPaymentMethod={selectedPaymentMethod}+ onSelectPaymentMethod={setSelectedPaymentMethod}+ onSelectAddNewPaymentMethod={() => {+ // [TODO] For now, use stripe's web portal to add payment method+ // redirectToPortal('/payment-methods')+ setShowAddPaymentMethodModal(true)+ // onSelectAddNewPaymentMethod()+ }}+ onConfirmPayment={onConfirmPayment}+ isSubmitting={isSubmitting}+ />+ </div>+ </></Transition><AddNewPaymentMethodModaldiff --git a/studio/components/interfaces/Billing/ProUpgrade/ProUpgrade.utils.ts b/studio/components/interfaces/Billing/ProUpgrade/ProUpgrade.utils.tsnew file mode 100644index 00000000000..9a20e68b4a9--- /dev/null+++ b/studio/components/interfaces/Billing/ProUpgrade/ProUpgrade.utils.ts@@ -0,0 +1,20 @@+export const formSubscriptionUpdatePayload = (+ selectedTier: any,+ selectedComputeSize: any,+ selectedPaymentMethod: string+) => {+ // [TODO] Small currently has no stripe product attached, so FE has a hardcoded ID just for that product+ // [UPDATE] it now has, just verify if attaching a Small will mess things up+ // const addons = selectedComputeSize.name.includes('[Small]')+ // ? []+ // : [selectedComputeSize.prices[0].id]+ const addons = [selectedComputeSize.prices[0].id]+ const proration_date = Math.floor(Date.now() / 1000)++ return {+ tier: selectedTier.prices[0].id,+ addons,+ proration_date,+ payment_method: selectedPaymentMethod,+ }+}diff --git a/studio/components/interfaces/Billing/index.ts b/studio/components/interfaces/Billing/index.tsindex fa9e9d6c0b7..9f85d2861a3 100644--- a/studio/components/interfaces/Billing/index.ts+++ b/studio/components/interfaces/Billing/index.ts@@ -2,7 +2,7 @@ import PAYGUsage from './PAYGUsage/PAYGUsage'import Subscription from './Subscription/Subscription'import PlanSelection from './PlanSelection/PlanSelection'-import ProUpgrade from './ProUpgrade'+import ProUpgrade from './ProUpgrade/ProUpgrade'import EnterpriseRequest from './EnterpriseRequest'import ExitSurvey from './ExitSurvey/ExitSurvey'import PaymentSummaryPanel from './PaymentSummaryPanel'diff --git a/studio/components/to-be-cleaned/Storage/StorageExplorer/ConfirmDeleteModal.js b/studio/components/to-be-cleaned/Storage/StorageExplorer/ConfirmDeleteModal.jsindex 3e251fc8d62..2d84e4c6d92 100644--- a/studio/components/to-be-cleaned/Storage/StorageExplorer/ConfirmDeleteModal.js+++ b/studio/components/to-be-cleaned/Storage/StorageExplorer/ConfirmDeleteModal.js@@ -1,5 +1,5 @@import { useEffect, useState } from 'react'-import { Modal, Button, Space, Alert } from '@supabase/ui'+import { Modal, Button, Alert } from '@supabase/ui'const ConfirmDeleteModal = ({visible = false,diff --git a/studio/components/ui/InformationBox.tsx b/studio/components/ui/InformationBox.tsxindex d9a69fc5f2c..f89b621ce44 100644--- a/studio/components/ui/InformationBox.tsx+++ b/studio/components/ui/InformationBox.tsx@@ -12,7 +12,6 @@ interface Props {button?: React.ReactNodeclassName?: stringblock?: boolean- size?: 'tiny' | 'small' | 'normal' | 'large'}const InformationBox: FC<Props> = ({@@ -26,12 +25,9 @@ const InformationBox: FC<Props> = ({button,className = '',block = false,- size = 'normal',}) => {const [isExpanded, setIsExpanded] = useState<boolean>(defaultVisibility)- const padding = { tiny: 'py-1', small: 'py-2', normal: 'py-3', large: 'py-4' }[size]-return (<divclassName={`${block ? 'block w-full' : ''}diff --git a/studio/lib/constants/index.ts b/studio/lib/constants/index.tsindex 1f714801ffd..53f992ef652 100644--- a/studio/lib/constants/index.ts+++ b/studio/lib/constants/index.ts@@ -82,4 +82,4 @@ export const GOTRUE_ERRORS = {}export const STRIPE_PUBLIC_KEY =- process.env.STRIPE_PUBLIC_KEY || 'pk_test_XVwg5IZH3I9Gti98hZw6KRzd00v5858heG'+ process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY || 'pk_test_XVwg5IZH3I9Gti98hZw6KRzd00v5858heG'diff --git a/studio/package-lock.json b/studio/package-lock.jsonindex 0ff234ff5cf..42e41e7335d 100644--- a/studio/package-lock.json+++ b/studio/package-lock.json@@ -16,7 +16,7 @@"@sentry/browser": "^6.15.0","@sentry/nextjs": "^6.15.0","@stripe/react-stripe-js": "^1.7.0",- "@stripe/stripe-js": "^1.24.0",+ "@stripe/stripe-js": "^1.25.0","@supabase/grid": "v2.5.0-alpha.8","@supabase/postgres-meta": "^0.26.1","@supabase/react-data-grid": "^7.1.0-beta.7",@@ -3394,9 +3394,9 @@}},"node_modules/@stripe/stripe-js": {- "version": "1.24.0",- "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-1.24.0.tgz",- "integrity": "sha512-8CEILOpzoRhGwvgcf6y+BlPyEq1ZqxAv3gsX7LvokFYvbcyH72GRcHQMGXuZS3s7HqfYQuTSFrvZNL/qdkgA9Q=="+ "version": "1.25.0",+ "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-1.25.0.tgz",+ "integrity": "sha512-cywIoKu3sJnBPQ1eKi3BzFHWslA2ePqHvQhcxp7iYYlo1tWcVgEKTSh7y7hb6GoR4TyT3DwlK4v1vOZpVg8u4Q=="},"node_modules/@supabase/gotrue-js": {"version": "1.21.7",@@ -16834,9 +16834,9 @@}},"@stripe/stripe-js": {- "version": "1.24.0",- "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-1.24.0.tgz",- "integrity": "sha512-8CEILOpzoRhGwvgcf6y+BlPyEq1ZqxAv3gsX7LvokFYvbcyH72GRcHQMGXuZS3s7HqfYQuTSFrvZNL/qdkgA9Q=="+ "version": "1.25.0",+ "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-1.25.0.tgz",+ "integrity": "sha512-cywIoKu3sJnBPQ1eKi3BzFHWslA2ePqHvQhcxp7iYYlo1tWcVgEKTSh7y7hb6GoR4TyT3DwlK4v1vOZpVg8u4Q=="},"@supabase/gotrue-js": {"version": "1.21.7",diff --git a/studio/package.json b/studio/package.jsonindex 44aeb2e8380..79751ced53b 100644--- a/studio/package.json+++ b/studio/package.json@@ -18,7 +18,7 @@"@sentry/browser": "^6.15.0","@sentry/nextjs": "^6.15.0","@stripe/react-stripe-js": "^1.7.0",- "@stripe/stripe-js": "^1.24.0",+ "@stripe/stripe-js": "^1.25.0","@supabase/grid": "v2.5.0-alpha.8","@supabase/postgres-meta": "^0.26.1","@supabase/react-data-grid": "^7.1.0-beta.7",diff --git a/studio/pages/project/[ref]/settings/billing/update/index.tsx b/studio/pages/project/[ref]/settings/billing/update/index.tsxindex 97a167351a7..0277e706938 100644--- a/studio/pages/project/[ref]/settings/billing/update/index.tsx+++ b/studio/pages/project/[ref]/settings/billing/update/index.tsx@@ -10,7 +10,7 @@ import { API_URL, DEFAULT_FREE_PROJECTS_LIMIT, STRIPE_PRODUCT_IDS } from 'lib/coimport { BillingLayout } from 'components/layouts'import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'-import { PlanSelection, ProUpgrade, StripeSubscription } from 'components/interfaces/Billing'+import { PlanSelection, StripeSubscription } from 'components/interfaces/Billing'import { BillingPlan } from 'components/interfaces/Billing/PlanSelection/Plans/Plans.types'import Connecting from 'components/ui/Loading/Loading'@@ -26,20 +26,17 @@ const BillingUpdate: NextPage = () => {const { ui } = useStore()const router = useRouter()const projectRef = ui.selectedProject?.ref- const stripeCustomerId = ui.selectedOrganization?.stripe_customer_idconst subscriptionStats = useSubscriptionStats()const freeProjectsLimit = ui?.profile?.free_project_limit ?? DEFAULT_FREE_PROJECTS_LIMITconst freeProjectsOwned = subscriptionStats.total_free_projects ?? 0const [isLoadingProducts, setIsLoadingProducts] = useState(false)- const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)const [showConfirmDowngrade, setShowConfirmDowngrade] = useState(false)const [showDowngradeError, setShowDowngradeError] = useState(false)const [products, setProducts] = useState<{ tiers: any[]; addons: any[] }>()const [subscription, setSubscription] = useState<StripeSubscription>()- const [paymentMethods, setPaymentMethods] = useState<any>()const [selectedPlan, setSelectedPlan] = useState<BillingPlan>()useEffect(() => {@@ -49,10 +46,8 @@ const BillingUpdate: NextPage = () => {}}, [projectRef])- useEffect(() => {- if (stripeCustomerId) getStripeAccount()- }, [stripeCustomerId])-+ // [Joshen] Perhaps we shift this fetch into the global mobx tree+ // Since all the pages require this data, makes more sense to load it once at the layoutconst getStripeProducts = async () => {try {setIsLoadingProducts(true)@@ -68,24 +63,6 @@ const BillingUpdate: NextPage = () => {}}- const getStripeAccount = async () => {- try {- setIsLoadingPaymentMethods(true)- const { paymentMethods, error: customerError } = await post(`${API_URL}/stripe/customer`, {- stripe_customer_id: stripeCustomerId,- })- if (customerError) throw customerError- setIsLoadingPaymentMethods(false)- setPaymentMethods(paymentMethods)- } catch (error: any) {- ui.setNotification({- error,- category: 'error',- message: `Failed to get subscription: ${error.message}`,- })- }- }-const getSubscription = async () => {try {if (!ui.selectedProject?.subscription_id) {@@ -111,10 +88,12 @@ const BillingUpdate: NextPage = () => {const onSelectPlan = (plan: BillingPlan) => {if (plan.name === 'Enterprise') {return router.push(`/project/${projectRef}/settings/billing/update/enterprise`)+ } else if (plan.id === STRIPE_PRODUCT_IDS.PRO) {+ return router.push(`/project/${projectRef}/settings/billing/update/pro`)}- setSelectedPlan(plan)if (plan.id === STRIPE_PRODUCT_IDS.FREE) {+ setSelectedPlan(plan)setShowConfirmDowngrade(true)}}@@ -147,21 +126,6 @@ const BillingUpdate: NextPage = () => {/></div>- {subscription !== undefined && products !== undefined && (- <ProUpgrade- visible={- selectedPlan?.id === STRIPE_PRODUCT_IDS.PRO ||- selectedPlan?.id === STRIPE_PRODUCT_IDS.PAYG- }- products={products}- currentSubscription={subscription}- selectedPlan={selectedPlan}- isLoadingPaymentMethods={isLoadingPaymentMethods}- paymentMethods={paymentMethods?.data ?? []}- onSelectBack={() => setSelectedPlan(undefined)}- />- )}-{/* [Joshen] Possible refactor, shift this into PlanSelection */}<ConfirmModaldangerdiff --git a/studio/pages/project/[ref]/settings/billing/update/pro.tsx b/studio/pages/project/[ref]/settings/billing/update/pro.tsxnew file mode 100644index 00000000000..f7e101242ea--- /dev/null+++ b/studio/pages/project/[ref]/settings/billing/update/pro.tsx@@ -0,0 +1,117 @@+import { useState, useEffect } from 'react'+import { NextPage } from 'next'+import { observer } from 'mobx-react-lite'+import { useRouter } from 'next/router'++import { withAuth, useStore } from 'hooks'+import { get, post } from 'lib/common/fetch'+import { API_URL, STRIPE_PRODUCT_IDS } from 'lib/constants'++import { BillingLayout } from 'components/layouts'+import Connecting from 'components/ui/Loading/Loading'+import { StripeSubscription } from 'components/interfaces/Billing'+import { ProUpgrade } from 'components/interfaces/Billing'++const BillingUpdatePro: NextPage = () => {+ const { ui } = useStore()+ const router = useRouter()+ const projectRef = ui.selectedProject?.ref+ const stripeCustomerId = ui.selectedOrganization?.stripe_customer_id++ const [isLoadingProducts, setIsLoadingProducts] = useState(false)+ const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)++ const [subscription, setSubscription] = useState<StripeSubscription>()+ const [products, setProducts] = useState<{ tiers: any[]; addons: any[] }>()+ const [paymentMethods, setPaymentMethods] = useState<any>()++ useEffect(() => {+ // User added a new payment method+ if (router.query.setup_intent && router.query.redirect_status) {+ ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })+ }+ }, [])++ useEffect(() => {+ if (projectRef) {+ getStripeProducts()+ getSubscription()+ }+ }, [projectRef])++ useEffect(() => {+ if (stripeCustomerId) getStripeAccount()+ }, [stripeCustomerId])++ const getStripeProducts = async () => {+ try {+ setIsLoadingProducts(true)+ const products = await get(`${API_URL}/stripe/products`)+ setProducts(products)+ setIsLoadingProducts(false)+ } catch (error: any) {+ ui.setNotification({+ error,+ category: 'error',+ message: `Failed to get products: ${error.message}`,+ })+ }+ }++ const getStripeAccount = async () => {+ try {+ setIsLoadingPaymentMethods(true)+ const { paymentMethods, error: customerError } = await post(`${API_URL}/stripe/customer`, {+ stripe_customer_id: stripeCustomerId,+ })+ if (customerError) throw customerError+ setIsLoadingPaymentMethods(false)+ setPaymentMethods(paymentMethods)+ } catch (error: any) {+ ui.setNotification({+ error,+ category: 'error',+ message: `Failed to get subscription: ${error.message}`,+ })+ }+ }++ const getSubscription = async () => {+ try {+ if (!ui.selectedProject?.subscription_id) {+ throw new Error('Unable to get subscription ID of project')+ }++ const { data: subscription, error }: { data: StripeSubscription; error: any } = await post(+ `${API_URL}/stripe/subscription`,+ { subscription_id: ui.selectedProject.subscription_id }+ )++ if (error) throw error+ setSubscription(subscription)+ } catch (error: any) {+ ui.setNotification({+ error,+ category: 'error',+ message: `Failed to get subscription: ${error.message}`,+ })+ }+ }++ // temp+ if (!products || !subscription) return <Connecting />++ return (+ <BillingLayout>+ <ProUpgrade+ products={products}+ currentSubscription={subscription}+ isLoadingPaymentMethods={isLoadingPaymentMethods}+ paymentMethods={paymentMethods?.data ?? []}+ onSelectBack={() => router.push(`/project/${projectRef}/settings/billing/update`)}+ />+ </BillingLayout>+ )+}++export default withAuth(observer(BillingUpdatePro))diff --git a/studio/pages/project/[ref]/settings/logs/[type].tsx b/studio/pages/project/[ref]/settings/logs/[type].tsxindex d69cf8ae186..464a67638fa 100644--- a/studio/pages/project/[ref]/settings/logs/[type].tsx+++ b/studio/pages/project/[ref]/settings/logs/[type].tsx@@ -269,7 +269,6 @@ export const LogPage: NextPage = () => {<InformationBoxclassName="shrink mr-auto"block={false}- size="tiny"icon={<IconInfo size="tiny" />}title={`Custom queries are restricted to a ${type === 'database' ? '2 hour' : '7 day'