The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Small refactors while testing project subscription mutations
Joshen Limd2d2b5d72ea5
diff --git a/studio/components/interfaces/Settings/Addons/Addons.tsx b/studio/components/interfaces/Settings/Addons/Addons.tsxindex 7f1df1285e7..673ff4e807a 100644--- a/studio/components/interfaces/Settings/Addons/Addons.tsx+++ b/studio/components/interfaces/Settings/Addons/Addons.tsx@@ -12,6 +12,8 @@ import {ScaffoldSectionContent,ScaffoldSectionDetail,} from 'components/layouts/Scaffold'+import AlertError from 'components/ui/AlertError'+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useInfraMonitoringQuery } from 'data/analytics/infra-monitoring-query'import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'import { useFlag } from 'hooks'@@ -19,8 +21,6 @@ import { BASE_PATH } from 'lib/constants'import { useSubscriptionPageStateSnapshot } from 'state/subscription-page'import { Alert, Button, IconChevronRight, IconExternalLink } from 'ui'import { ComputeInstanceSidePanel, CustomDomainSidePanel, PITRSidePanel } from './'-import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'-import AlertError from 'components/ui/AlertError'const Addons = () => {const { isDarkMode } = useTheme()diff --git a/studio/components/interfaces/Settings/General/General.tsx b/studio/components/interfaces/Settings/General/General.tsxindex caf145a67fd..2dfc7b1c922 100644--- a/studio/components/interfaces/Settings/General/General.tsx+++ b/studio/components/interfaces/Settings/General/General.tsx@@ -1,5 +1,4 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useQueryClient } from '@tanstack/react-query'import Link from 'next/link'import { Button, Form, IconBarChart2, Input } from 'ui'@@ -14,16 +13,13 @@ import {} from 'components/ui/Forms'import Panel from 'components/ui/Panel'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'-import { invalidateProjectsQuery } from 'data/projects/projects-query'+import { useProjectUpdateMutation } from 'data/projects/project-update-mutation'import { useCheckPermissions, useSelectedOrganization, useStore } from 'hooks'-import { patch } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'import PauseProjectButton from './Infrastructure/PauseProjectButton'import RestartServerButton from './Infrastructure/RestartServerButton'const General = () => {const { ui } = useStore()- const queryClient = useQueryClient()const { project } = useProjectContext()const organization = useSelectedOrganization()@@ -31,26 +27,17 @@ const General = () => {const formId = 'project-general-settings'const initialValues = { name: project?.name ?? '', ref: project?.ref ?? '' }const canUpdateProject = useCheckPermissions(PermissionAction.UPDATE, 'projects')+ const { mutateAsync: updateProject, isLoading: isUpdating } = useProjectUpdateMutation()const onSubmit = async (values: any, { resetForm }: any) => {- const response = await patch(`${API_URL}/projects/${project?.ref}`, {- name: values.name.trim(),- })- if (response.error) {- ui.setNotification({- category: 'error',- message: `Update project failed: ${response.error.message}`,- })- } else {- const { name } = response- resetForm({ values: { name }, initialValues: { name } })+ if (!project?.ref) return console.error('Ref is required')- await invalidateProjectsQuery(queryClient)- ui.setNotification({- category: 'success',- message: 'Successfully saved settings',- })- }+ const { name } = await updateProject({ ref: project.ref, name: values.name.trim() })+ resetForm({ values: { name }, initialValues: { name } })+ ui.setNotification({+ category: 'success',+ message: 'Successfully saved settings',+ })}return (@@ -60,7 +47,7 @@ const General = () => {<GenericSkeletonLoader />) : (<Form id={formId} initialValues={initialValues} onSubmit={onSubmit}>- {({ isSubmitting, handleReset, values, initialValues }: any) => {+ {({ handleReset, values, initialValues }: any) => {const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)return (<FormPanel@@ -69,7 +56,7 @@ const General = () => {<div className="flex py-4 px-8"><FormActionsform={formId}- isSubmitting={isSubmitting}+ isSubmitting={isUpdating}hasChanges={hasChanges}handleReset={handleReset}helper={diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsxindex b56940ded52..80152718fc4 100644--- a/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/ProjectDropdown.tsx@@ -6,6 +6,8 @@ import { Button, Dropdown, IconPlus, Popover } from 'ui'import { useProjectsQuery } from 'data/projects/projects-query'import { useSelectedOrganization, useSelectedProject } from 'hooks'import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'+import { Organization, Project } from 'types'+import { useOrganizationsQuery } from 'data/organizations/organizations-query'// [Fran] the idea is to let users change projects without losing the current page,// but at the same time we need to redirect correctly between urls that might be@@ -30,13 +32,51 @@ export const sanitizeRoute = (route: string, routerQueries: ParsedUrlQuery) => {}}+const ProjectLink = ({+ project,+ organization,+}: {+ project: Project+ organization?: Organization+}) => {+ const router = useRouter()+ const selectedProject = useSelectedProject()+ const sanitizedRoute = sanitizeRoute(router.route, router.query)+ const isOrgBilling = !!organization?.subscription_id++ // [Joshen] Temp while we're interim between v1 and v2 billing+ let href = sanitizedRoute?.replace('[ref]', project.ref) ?? `/project/${project.ref}`+ if (href.endsWith('settings/addons') && !isOrgBilling) {+ href = href.replace('settings/addons', 'settings/billing/subscription')+ } else if (href.endsWith('settings/billing/subscription') && isOrgBilling) {+ href = href.replace('settings/billing/subscription', 'settings/addons')+ } else if (href.endsWith('settings/infrastructure') && !isOrgBilling) {+ href = href.replace('settings/infrastructure', 'settings/billing/usage')+ } else if (href.endsWith('settings/billing/usage') && !isOrgBilling) {+ href = href.replace('settings/billing/usage', 'settings/infrastructure')+ }++ return (+ <Link passHref href={href}>+ <a className="block">+ <Dropdown.Item+ className={+ selectedProject?.name === project.name ? 'font-bold bg-slate-400 dark:bg-slate-500' : ''+ }+ >+ {project.name}+ </Dropdown.Item>+ </a>+ </Link>+ )+}+const ProjectDropdown = () => {- const selectedOrganization = useSelectedOrganization()const selectedProject = useSelectedProject()+ const selectedOrganization = useSelectedOrganization()const { data: allProjects } = useProjectsQuery()+ const { data: allOrganizations } = useOrganizationsQuery()const selectedOrganizationSlug = selectedOrganization?.slug- const router = useRouter()- const sanitizedRoute = sanitizeRoute(router.route, router.query)return IS_PLATFORM ? (<Dropdown@@ -47,25 +87,10 @@ const ProjectDropdown = () => {{allProjects?.filter((x) => x.status !== PROJECT_STATUS.INACTIVE).sort((a, b) => a.name.localeCompare(b.name))- .map((x) => (- <Link- key={x.ref}- href={sanitizedRoute?.replace('[ref]', x.ref) ?? `/project/${x.ref}`}- passHref- >- <a className="block">- <Dropdown.Item- className={- selectedProject?.name === x.name- ? 'font-bold bg-slate-400 dark:bg-slate-500'- : ''- }- >- {x.name}- </Dropdown.Item>- </a>- </Link>- ))}+ .map((x) => {+ const org = allOrganizations?.find((org) => org.id === x.organization_id)+ return <ProjectLink key={x.ref} project={x} organization={org} />+ })}<Popover.Separator /><Link href={`/new/${selectedOrganizationSlug}`}><a className="block">diff --git a/studio/components/ui/UpgradeToPro.tsx b/studio/components/ui/UpgradeToPro.tsxindex 75236f67f88..55a8becd771 100644--- a/studio/components/ui/UpgradeToPro.tsx+++ b/studio/components/ui/UpgradeToPro.tsx@@ -53,7 +53,7 @@ const UpgradeToPro: FC<Props> = ({ icon, primaryText, projectRef, secondaryText}`}><a>- {tier === PRICING_TIER_PRODUCT_IDS.FREE ? 'Upgrade to Pro' : 'Enable Addon'}+ {tier === PRICING_TIER_PRODUCT_IDS.FREE ? 'Upgrade to Pro' : 'Enable add on'}</a></Link></Button>diff --git a/studio/data/organizations/organizations-query.ts b/studio/data/organizations/organizations-query.tsindex c58439c1f60..98a2795b55b 100644--- a/studio/data/organizations/organizations-query.ts+++ b/studio/data/organizations/organizations-query.ts@@ -2,12 +2,10 @@ import { QueryClient, useQuery, useQueryClient, UseQueryOptions } from '@tanstacimport { get } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { useCallback } from 'react'-import { Organization } from 'types'+import { Organization, ResponseError } from 'types'import { organizationKeys } from './keys'-export type OrganizationsResponse = Organization[]--export async function getOrganizations(signal?: AbortSignal): Promise<OrganizationsResponse> {+export async function getOrganizations(signal?: AbortSignal): Promise<Organization[]> {const data = await get(`${API_URL}/organizations`, { signal })if (data.error) throw data.error@@ -17,7 +15,7 @@ export async function getOrganizations(signal?: AbortSignal): Promise<Organizati}export type OrganizationsData = Awaited<ReturnType<typeof getOrganizations>>-export type OrganizationsError = unknown+export type OrganizationsError = ResponseErrorexport const useOrganizationsQuery = <TData = OrganizationsData>({enabled = true,diff --git a/studio/data/projects/project-update-mutation.ts b/studio/data/projects/project-update-mutation.tsnew file mode 100644index 00000000000..4e9db8c8a78--- /dev/null+++ b/studio/data/projects/project-update-mutation.ts@@ -0,0 +1,55 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { patch } from 'lib/common/fetch'+import { API_URL } from 'lib/constants'+import { ResponseError } from 'types'+import { projectKeys } from './keys'++export type ProjectUpdateVariables = {+ ref: string+ name: string+}++export type ProjectUpdateResponse = {+ id: number+ ref: string+ name: string+}++export async function updateProject({ ref, name }: ProjectUpdateVariables) {+ const response = await patch(`${API_URL}/projects/${ref}`, { name })+ if (response.error) throw response.error+ return response as ProjectUpdateResponse+}++type ProjectUpdateData = Awaited<ReturnType<typeof updateProject>>++export const useProjectUpdateMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<ProjectUpdateData, ResponseError, ProjectUpdateVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<ProjectUpdateData, ResponseError, ProjectUpdateVariables>(+ (vars) => updateProject(vars),+ {+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries(projectKeys.list()),+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update project: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/studio/pages/project/[ref]/settings/addons.tsx b/studio/pages/project/[ref]/settings/addons.tsxindex dd4c1b800dd..db292501c79 100644--- a/studio/pages/project/[ref]/settings/addons.tsx+++ b/studio/pages/project/[ref]/settings/addons.tsx@@ -1,8 +1,34 @@+import { useParams } from 'common'import Addons from 'components/interfaces/Settings/Addons'import { SettingsLayout } from 'components/layouts'+import { useSelectedOrganization } from 'hooks'+import Link from 'next/link'import { NextPageWithLayout } from 'types'+import { Alert } from 'ui'const ProjectAddons: NextPageWithLayout = () => {+ const { ref } = useParams()+ const organization = useSelectedOrganization()+ const isOrgBilling = !!organization?.subscription_id++ if (!isOrgBilling) {+ return (+ <div className="p-4">+ <Alert+ withIcon+ variant="info"+ title="This page is only available for projects under an organization subscription"+ >+ You might be looking for the{' '}+ <Link href={`/project/${ref}/settings/billing/subscription`}>+ <a className="text-brand-900">project's subscription</a>+ </Link>{' '}+ page instead.+ </Alert>+ </div>+ )+ }+return <Addons />}diff --git a/studio/pages/project/[ref]/settings/billing/invoices.tsx b/studio/pages/project/[ref]/settings/billing/invoices.tsxindex 2f4148fdf9f..7b50f1e3c0f 100644--- a/studio/pages/project/[ref]/settings/billing/invoices.tsx+++ b/studio/pages/project/[ref]/settings/billing/invoices.tsx@@ -5,8 +5,30 @@ import { SettingsLayout } from 'components/layouts'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import { useSelectedOrganization } from 'hooks'import { NextPageWithLayout } from 'types'+import { Alert } from 'ui'const ProjectBilling: NextPageWithLayout = () => {+ const organization = useSelectedOrganization()+ const isOrgBilling = !!organization?.subscription_id++ if (isOrgBilling) {+ return (+ <div className="p-4">+ <Alert+ withIcon+ variant="info"+ title="This page is only available for projects which are on their own subscription"+ >+ You might be looking for the{' '}+ <Link href={`/org/${organization?.slug}/invoices`}>+ <a className="text-brand-900">organization's invoices</a>+ </Link>{' '}+ page instead.+ </Alert>+ </div>+ )+ }+return (<div className="w-full h-full overflow-y-auto content"><div className="w-full mx-auto">diff --git a/studio/pages/project/[ref]/settings/billing/subscription.tsx b/studio/pages/project/[ref]/settings/billing/subscription.tsxindex 7bf85a086f7..d787c003404 100644--- a/studio/pages/project/[ref]/settings/billing/subscription.tsx+++ b/studio/pages/project/[ref]/settings/billing/subscription.tsx@@ -1,10 +1,33 @@-import { observer } from 'mobx-react-lite'+import Link from 'next/link'import SubscriptionV2 from 'components/interfaces/BillingV2/Subscription/Subscription'import { SettingsLayout } from 'components/layouts'+import { useSelectedOrganization } from 'hooks'import { NextPageWithLayout } from 'types'+import { Alert } from 'ui'const ProjectBilling: NextPageWithLayout = () => {+ const organization = useSelectedOrganization()+ const isOrgBilling = !!organization?.subscription_id++ if (isOrgBilling) {+ return (+ <div className="p-4">+ <Alert+ withIcon+ variant="info"+ title="This page is only available for projects which are on their own subscription"+ >+ Subscription management can be found on the{' '}+ <Link href={`/org/${organization?.slug}/billing`}>+ <a className="text-brand-900">organization's billing</a>+ </Link>{' '}+ page instead.+ </Alert>+ </div>+ )+ }+return <SubscriptionV2 />}@@ -12,4 +35,4 @@ ProjectBilling.getLayout = (page) => (<SettingsLayout title="Billing and Usage">{page}</SettingsLayout>)-export default observer(ProjectBilling)+export default ProjectBillingdiff --git a/studio/pages/project/[ref]/settings/billing/usage.tsx b/studio/pages/project/[ref]/settings/billing/usage.tsxindex 23d65446ef8..2332a1f371f 100644--- a/studio/pages/project/[ref]/settings/billing/usage.tsx+++ b/studio/pages/project/[ref]/settings/billing/usage.tsx@@ -1,10 +1,35 @@-import { observer } from 'mobx-react-lite'+import Link from 'next/link'-import { NextPageWithLayout } from 'types'-import { SettingsLayout } from 'components/layouts'import Usage from 'components/interfaces/BillingV2/Usage/Usage'+import { SettingsLayout } from 'components/layouts'+import { useSelectedOrganization } from 'hooks'+import { NextPageWithLayout } from 'types'+import { Alert } from 'ui'+import { useParams } from 'common'const ProjectBillingUsage: NextPageWithLayout = () => {+ const { ref } = useParams()+ const organization = useSelectedOrganization()+ const isOrgBilling = !!organization?.subscription_id++ if (isOrgBilling) {+ return (+ <div className="p-4">+ <Alert+ withIcon+ variant="info"+ title="This page is only available for projects which are on their own subscription"+ >+ Project usage statistics have been shifted to the{' '}+ <Link href={`/org/${organization?.slug}/usage?projectRef=${ref}`}>+ <a className="text-brand-900">organization's usage</a>+ </Link>{' '}+ page instead.+ </Alert>+ </div>+ )+ }+return <Usage />}@@ -12,4 +37,4 @@ ProjectBillingUsage.getLayout = (page) => (<SettingsLayout title="Billing and Usage">{page}</SettingsLayout>)-export default observer(ProjectBillingUsage)+export default ProjectBillingUsagediff --git a/studio/pages/project/[ref]/settings/infrastructure.tsx b/studio/pages/project/[ref]/settings/infrastructure.tsxindex a5456c9de88..629177a1dcc 100644--- a/studio/pages/project/[ref]/settings/infrastructure.tsx+++ b/studio/pages/project/[ref]/settings/infrastructure.tsx@@ -1,10 +1,36 @@+import { useParams } from 'common'import InfrastructureActivity from 'components/interfaces/Settings/Infrastructure/InfrastructureActivity'import InfrastructureInfo from 'components/interfaces/Settings/Infrastructure/InfrastructureInfo'import { SettingsLayout } from 'components/layouts'import { ScaffoldDivider } from 'components/layouts/Scaffold'+import { useSelectedOrganization } from 'hooks'+import Link from 'next/link'import { NextPageWithLayout } from 'types'+import { Alert } from 'ui'const ProjectInfrastructure: NextPageWithLayout = () => {+ const { ref } = useParams()+ const organization = useSelectedOrganization()+ const isOrgBilling = !!organization?.subscription_id++ if (!isOrgBilling) {+ return (+ <div className="p-4">+ <Alert+ withIcon+ variant="info"+ title="This page is only available for projects under an organization subscription"+ >+ You might be looking for the{' '}+ <Link href={`/project/${ref}/settings/billing/usage`}>+ <a className="text-brand-900">project's usage</a>+ </Link>{' '}+ page instead.+ </Alert>+ </div>+ )+ }+return (<><InfrastructureInfo />