Skip to content

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

feat: create useSubscriptionStats hook

phamhieu2c86968b2051
diff --git a/studio/components/interfaces/Billing/Subscription/Subscription.tsx b/studio/components/interfaces/Billing/Subscription/Subscription.tsx
index 615c5900279..c120e543587 100644
--- a/studio/components/interfaces/Billing/Subscription/Subscription.tsx
+++ b/studio/components/interfaces/Billing/Subscription/Subscription.tsx
@@ -11,10 +11,12 @@ import { chargeableProducts } from '../PAYGUsage/PAYGUsage.constants'
import { formatBytes } from 'lib/helpers'
import { STRIPE_PRODUCT_IDS } from 'lib/constants'
import { Dictionary } from '@supabase/grid'
+import { SubscriptionStats } from 'hooks'
interface Props {
project: any
subscription: StripeSubscription
+ subscriptionStats: SubscriptionStats
paygStats?: Dictionary<number>
loading?: boolean
showProjectName?: boolean
@@ -25,6 +27,7 @@ interface Props {
const Subscription: FC<Props> = ({
project,
subscription,
+ subscriptionStats,
paygStats,
loading = false,
showProjectName = false,
@@ -59,7 +62,11 @@ const Subscription: FC<Props> = ({
</Typography.Title>
</div>
{/* @ts-ignore */}
- <UpgradeButton projectRef={project.ref} paid={paid} />
+ <UpgradeButton
+ subscriptionStats={subscriptionStats}
+ projectRef={project.ref}
+ paid={paid}
+ />
</div>
{paid && (
<div className="px-6 pt-4">
diff --git a/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx b/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx
index 388f540cdc3..4fcce39815d 100644
--- a/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx
+++ b/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx
@@ -1,9 +1,9 @@
-import React, { useReducer, useState } from 'react'
+import { FC, useReducer, useState } from 'react'
import { useRouter } from 'next/router'
import { includes, without } from 'lodash'
import { Button, Modal, Input, Divider, Typography, IconCheckCircle } from '@supabase/ui'
-import { useStore } from 'hooks'
+import { SubscriptionStats, useStore } from 'hooks'
import { API_URL, DEFAULT_FREE_PROJECTS_LIMIT } from 'lib/constants'
import { getURL } from 'lib/helpers'
import { post } from 'lib/common/fetch'
@@ -16,7 +16,13 @@ import { CancellationReasons } from './SubcriptionCancellation.constants'
* @param {Boolean} props.paid Tier name
*/
-export default function UpgradeButton({ projectRef, paid }: any) {
+interface Props {
+ projectRef: string
+ paid: boolean
+ subscriptionStats: SubscriptionStats
+}
+
+const UpgradeButton: FC<Props> = ({ projectRef, paid, subscriptionStats }) => {
const router = useRouter()
const { ui, app } = useStore()
const [loading, setLoading] = useState<boolean>(false)
@@ -24,7 +30,7 @@ export default function UpgradeButton({ projectRef, paid }: any) {
const [showFreeProjectLimitWarning, setShowFreeProjectLimitWarning] = useState<boolean>(false)
const freeProjectsLimit = ui?.profile?.free_project_limit ?? DEFAULT_FREE_PROJECTS_LIMIT
- const freeProjectsOwned = ui?.profile?.total_free_projects ?? 0
+ const freeProjectsOwned = subscriptionStats.total_free_projects ?? 0
const isOrgOwner = ui.selectedOrganization?.is_owner
/**
@@ -49,7 +55,7 @@ export default function UpgradeButton({ projectRef, paid }: any) {
function handleUpgradeButton() {
if (paid) {
- if (freeProjectsOwned >= DEFAULT_FREE_PROJECTS_LIMIT) {
+ if (freeProjectsOwned >= freeProjectsLimit) {
setShowFreeProjectLimitWarning(true)
} else {
setExitSurveyVisible(true)
@@ -106,6 +112,8 @@ export default function UpgradeButton({ projectRef, paid }: any) {
)
}
+export default UpgradeButton
+
function UnsubcribeExitSurvey({ visible, setVisible, handleDowngrade }: any) {
const router = useRouter()
const { ref } = router.query
diff --git a/studio/components/interfaces/Organization/BillingSettings/ProjectSubscription.tsx b/studio/components/interfaces/Organization/BillingSettings/ProjectSubscription.tsx
index 54624131313..c6c7d604b37 100644
--- a/studio/components/interfaces/Organization/BillingSettings/ProjectSubscription.tsx
+++ b/studio/components/interfaces/Organization/BillingSettings/ProjectSubscription.tsx
@@ -3,7 +3,7 @@ import dayjs from 'dayjs'
import { get as _get, maxBy } from 'lodash'
import utc from 'dayjs/plugin/utc'
-import { useStore } from 'hooks'
+import { useStore, useSubscriptionStats } from 'hooks'
import { API_URL } from 'lib/constants'
import { Dictionary } from '@supabase/grid'
import { get, post } from 'lib/common/fetch'
@@ -18,6 +18,8 @@ interface Props {
const ProjectSubscription: FC<Props> = ({ project }) => {
const { ui } = useStore()
+ const subscriptionStats = useSubscriptionStats()
+
const [loading, setLoading] = useState<boolean>(true)
const [subscription, setSubscription] = useState<StripeSubscription>()
const [paygStats, setPaygStats] = useState<Dictionary<number>>()
@@ -81,6 +83,7 @@ const ProjectSubscription: FC<Props> = ({ project }) => {
// @ts-ignore
subscription={subscription}
paygStats={paygStats}
+ subscriptionStats={subscriptionStats}
// @ts-ignore
currentPeriodStart={subscription?.billing.current_period_start}
// @ts-ignore
diff --git a/studio/hooks/queries/index.ts b/studio/hooks/queries/index.ts
index 2e1effbdaf7..34c5ae8d600 100644
--- a/studio/hooks/queries/index.ts
+++ b/studio/hooks/queries/index.ts
@@ -1,3 +1,4 @@
export * from './useOrganizationDetail'
export * from './useProfile'
export * from './useProjectAuthConfig'
+export * from './useSubscriptionStats'
diff --git a/studio/hooks/queries/useSubscriptionStats.ts b/studio/hooks/queries/useSubscriptionStats.ts
new file mode 100644
index 00000000000..3557413d527
--- /dev/null
+++ b/studio/hooks/queries/useSubscriptionStats.ts
@@ -0,0 +1,25 @@
+import useSWR, { mutate } from 'swr'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+
+export interface SubscriptionStats {
+ total_paid_projects: number
+ total_free_projects: number
+ total_pro_projects: number
+ total_payg_projects: number
+}
+
+export function useSubscriptionStats() {
+ const url = `${API_URL}/profile/subscriptions`
+ const { data, error } = useSWR<any>(url, get)
+ const anyError = data?.error || error
+
+ return {
+ total_paid_projects: data?.total_paid_projects ?? 0,
+ total_free_projects: data?.total_free_projects ?? 0,
+ total_pro_projects: data?.total_pro_projects ?? 0,
+ total_payg_projects: data?.total_payg_projects ?? 0,
+ isLoading: !anyError && !data,
+ isError: !!anyError,
+ }
+}
diff --git a/studio/pages/new/[slug].tsx b/studio/pages/new/[slug].tsx
index 0f8a6baf269..7bde202f6cc 100644
--- a/studio/pages/new/[slug].tsx
+++ b/studio/pages/new/[slug].tsx
@@ -10,7 +10,7 @@ import { observer } from 'mobx-react-lite'
import { Button, Typography, Listbox, IconUsers, IconAlertCircle } from '@supabase/ui'
import { API_URL } from 'lib/constants'
-import { post, get } from 'lib/common/fetch'
+import { post } from 'lib/common/fetch'
import {
PROVIDERS,
REGIONS,
@@ -30,6 +30,7 @@ import Panel from 'components/to-be-cleaned/Panel'
import InformationBox from 'components/ui/InformationBox'
import { passwordStrength } from 'lib/helpers'
import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
+import { useSubscriptionStats } from 'hooks'
interface StripeCustomer {
paymentMethods: any
@@ -37,13 +38,6 @@ interface StripeCustomer {
error?: any
}
-interface SubscriptionStats {
- total_paid_projects: number
- total_free_projects: number
- total_pro_projects: number
- total_payg_projects: number
-}
-
async function fetchStripeAccount(stripeCustomerId: string) {
try {
const customer = await post(`${API_URL}/stripe/customer`, {
@@ -56,16 +50,6 @@ async function fetchStripeAccount(stripeCustomerId: string) {
}
}
-async function fetchProfileSubscriptionStats() {
- try {
- const subscriptions = await get(`${API_URL}/profile/subscriptions`)
- if (subscriptions.error) throw subscriptions.error
- return subscriptions
- } catch (error: any) {
- return { error }
- }
-}
-
export const PageLayout = () => {
return <Wizard />
}
@@ -77,6 +61,8 @@ export const Wizard = observer(() => {
const { slug } = router.query
const { app, ui } = useStore()
+ const subscriptionStats = useSubscriptionStats()
+
const [projectName, setProjectName] = useState('')
const [dbPass, setDbPass] = useState('')
const [dbRegion, setDbRegion] = useState(REGIONS_DEFAULT)
@@ -86,15 +72,12 @@ export const Wizard = observer(() => {
const [passwordStrengthWarning, setPasswordStrengthWarning] = useState('')
const [passwordStrengthScore, setPasswordStrengthScore] = useState(0)
const [stripeCustomer, setStripeCustomer] = useState<StripeCustomer | undefined>(undefined)
- const [subscriptionStats, setSubscriptionStats] = useState<SubscriptionStats | undefined>(
- undefined
- )
const organizations = values(toJS(app.organizations.list()))
const currentOrg = organizations.find((o: any) => o.slug === slug)
const stripeCustomerId = currentOrg?.stripe_customer_id
- const totalFreeProjects = subscriptionStats?.total_free_projects ?? 0
+ const totalFreeProjects = subscriptionStats.total_free_projects
const freeProjectsLimit = ui.profile?.free_project_limit ?? DEFAULT_FREE_PROJECTS_LIMIT
const isEmptyOrganizations = organizations.length <= 0
@@ -107,7 +90,7 @@ export const Wizard = observer(() => {
const canCreateProject =
currentOrg?.is_owner &&
- subscriptionStats != undefined &&
+ (subscriptionStats.isError || subscriptionStats.isLoading) &&
(!isSelectFreeTier || (isSelectFreeTier && !isOverFreeProjectLimit))
const canSubmit =
@@ -150,17 +133,6 @@ export const Wizard = observer(() => {
}
}, [stripeCustomerId])
- useEffect(() => {
- async function loadProfileSubscriptionStatsAsync() {
- const res = await fetchProfileSubscriptionStats()
- if (!res.error) {
- setSubscriptionStats(res)
- }
- }
-
- loadProfileSubscriptionStatsAsync()
- }, [])
-
function onProjectNameChange(e: any) {
e.target.value = e.target.value.replace(/\./g, '')
setProjectName(e.target.value)
diff --git a/studio/pages/project/[ref]/settings/billing.tsx b/studio/pages/project/[ref]/settings/billing.tsx
index 01fdaaa8482..02162eb8933 100644
--- a/studio/pages/project/[ref]/settings/billing.tsx
+++ b/studio/pages/project/[ref]/settings/billing.tsx
@@ -6,7 +6,7 @@ import { get as _get, maxBy } from 'lodash'
import { Dictionary } from '@supabase/grid'
import { API_URL } from 'lib/constants'
-import { useStore, withAuth } from 'hooks'
+import { useStore, useSubscriptionStats, withAuth } from 'hooks'
import { post, get } from 'lib/common/fetch'
import {
DATE_FORMAT,
@@ -51,6 +51,8 @@ const Settings: FC<SettingsProps> = ({ project }) => {
const { ui } = useStore()
const projectRef = ui.selectedProject?.ref
+ const subscriptionStats = useSubscriptionStats()
+
const [loading, setLoading] = useState<boolean>(true)
const [subscription, setSubscription] = useState<StripeSubscription>()
const [paygStats, setPaygStats] = useState<Dictionary<number>>()
@@ -121,6 +123,7 @@ const Settings: FC<SettingsProps> = ({ project }) => {
project={project}
subscription={subscription}
paygStats={paygStats}
+ subscriptionStats={subscriptionStats}
currentPeriodStart={subscription?.billing.current_period_start}
currentPeriodEnd={subscription?.billing.current_period_end}
/>