The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Port over the changes from https://github.com/supabase/supabase/pull/4586
Joshen Lim7192c8b29527
diff --git a/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx b/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsxindex c4cc3dd4069..388f540cdc3 100644--- a/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx+++ b/studio/components/interfaces/Billing/Subscription/UpgradeButton.tsx@@ -1,10 +1,10 @@import React, { useReducer, useState } from 'react'import { useRouter } from 'next/router'import { includes, without } from 'lodash'-import { Button, Modal, Input, Divider, Typography } from '@supabase/ui'+import { Button, Modal, Input, Divider, Typography, IconCheckCircle } from '@supabase/ui'import { useStore } from 'hooks'-import { API_URL } from 'lib/constants'+import { API_URL, DEFAULT_FREE_PROJECTS_LIMIT } from 'lib/constants'import { getURL } from 'lib/helpers'import { post } from 'lib/common/fetch'import { CancellationReasons } from './SubcriptionCancellation.constants'@@ -18,9 +18,14 @@ import { CancellationReasons } from './SubcriptionCancellation.constants'export default function UpgradeButton({ projectRef, paid }: any) {const router = useRouter()- const { ui } = useStore()+ const { ui, app } = useStore()const [loading, setLoading] = useState<boolean>(false)const [exitSurveyVisible, setExitSurveyVisible] = useState<boolean>(false)+ 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 isOrgOwner = ui.selectedOrganization?.is_owner/*** Get a link and then redirect them@@ -44,7 +49,11 @@ export default function UpgradeButton({ projectRef, paid }: any) {function handleUpgradeButton() {if (paid) {- setExitSurveyVisible(true)+ if (freeProjectsOwned >= DEFAULT_FREE_PROJECTS_LIMIT) {+ setShowFreeProjectLimitWarning(true)+ } else {+ setExitSurveyVisible(true)+ }} else {redirectToPortal()}@@ -57,9 +66,42 @@ export default function UpgradeButton({ projectRef, paid }: any) {setVisible={setExitSurveyVisible}handleDowngrade={redirectToPortal}/>- <Button onClick={handleUpgradeButton} type={paid ? 'outline' : 'primary'} loading={loading}>- {paid ? 'Cancel subscription' : 'Upgrade to Pro'}- </Button>+ <Modal+ closable+ visible={showFreeProjectLimitWarning}+ onCancel={() => setShowFreeProjectLimitWarning(false)}+ title="Free project limit reached"+ description="Please delete one of your free projects to downgrade this project back to free tier"+ size="tiny"+ showIcon+ layout="vertical"+ customFooter={+ <div className="flex w-full items-end">+ <Button+ block+ icon={<IconCheckCircle strokeWidth={2} />}+ onClick={() => setShowFreeProjectLimitWarning(false)}+ >+ OK+ </Button>+ </div>+ }+ />+ <div className="flex flex-col items-end space-y-2">+ <Button+ disabled={!isOrgOwner}+ onClick={handleUpgradeButton}+ type={paid ? 'secondary' : 'primary'}+ loading={loading}+ >+ {paid ? 'Cancel subscription' : 'Upgrade to Pro'}+ </Button>+ {!isOrgOwner && (+ <Typography.Text type="secondary" small>+ Only the organization owner can amend subscriptions+ </Typography.Text>+ )}+ </div></>)}diff --git a/studio/hooks/queries/useProfile.ts b/studio/hooks/queries/useProfile.tsindex 941e1dfe6ce..62782c163c8 100644--- a/studio/hooks/queries/useProfile.ts+++ b/studio/hooks/queries/useProfile.ts@@ -19,7 +19,11 @@ export function useProfile(returning?: 'minimal') {function mutateProfile(updatedUser: User, revalidate?: boolean) {mutate(url,- { first_name: updatedUser.first_name, last_name: updatedUser.last_name },+ {+ first_name: updatedUser.first_name,+ last_name: updatedUser.last_name,+ total_free_projects: updatedUser.total_free_projects,+ },revalidate ?? true)}diff --git a/studio/lib/constants/infrastructure.ts b/studio/lib/constants/infrastructure.tsindex 00cd4eb3dc8..f37b728cafd 100644--- a/studio/lib/constants/infrastructure.ts+++ b/studio/lib/constants/infrastructure.ts@@ -130,3 +130,5 @@ export const PASSWORD_STRENGTH_PERCENTAGE = {3: '80%',4: '100%',}++export const DEFAULT_FREE_PROJECTS_LIMIT = 2diff --git a/studio/pages/index.tsx b/studio/pages/index.tsxindex 8c1965fe4aa..2611ff1f69b 100644--- a/studio/pages/index.tsx+++ b/studio/pages/index.tsx@@ -6,9 +6,9 @@ import { isUndefined } from 'lodash'import { Typography } from '@supabase/ui'import { Project } from 'types'-import { useStore, withAuth } from 'hooks'+import { useProfile, useStore, withAuth } from 'hooks'import { post, delete_ } from 'lib/common/fetch'-import { API_URL, IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'+import { API_URL, IS_PLATFORM, PROJECT_STATUS, STRIPE_PRODUCT_IDS } from 'lib/constants'import { AccountLayout } from 'components/layouts'import Landing from 'components/interfaces/Home/Landing'import ProjectList from 'components/interfaces/Home/ProjectList'@@ -20,6 +20,7 @@ const Home: NextPage = () => {const { profile } = uiconst router = useRouter()+ const { mutateProfile } = useProfile()const [isDeletingProject, setIsDeletingProject] = useState<boolean>(false)const [selectedProjectToDelete, setSelectedProjectToDelete] = useState<Project>()@@ -41,7 +42,7 @@ const Home: NextPage = () => {return ui.setNotification({ category: 'error', message: response.error.message })}- app.onProjectDeleted(response)+ app.onProjectDeleted(response, mutateProfile)ui.setNotification({ category: 'success', message: `Deleted ${project.name} successfully!` })setIsDeletingProject(false)diff --git a/studio/pages/new/[slug].tsx b/studio/pages/new/[slug].tsxindex 5fce049a61c..195c6b7c606 100644--- a/studio/pages/new/[slug].tsx+++ b/studio/pages/new/[slug].tsx@@ -28,6 +28,7 @@ import {PASSWORD_STRENGTH_PERCENTAGE,PRICING_PLANS,PRICING_PLANS_DEFAULT,+ DEFAULT_FREE_PROJECTS_LIMIT,} from 'lib/constants'import { useStore, withAuth } from 'hooks'@@ -80,19 +81,28 @@ export const Wizard = observer(() => {const organizations = values(toJS(app.organizations.list()))const currentOrg = organizations.find((o: any) => o.slug === slug)const stripeCustomerId = currentOrg?.stripe_customer_id++ const totalFreeProjects = ui.profile?.total_free_projects ?? 0+ const freeProjectsLimit = ui.profile?.free_project_limit ?? DEFAULT_FREE_PROJECTS_LIMIT+const isEmptyOrganizations = organizations.length <= 0const isEmptyPaymentMethod = stripeCustomer? stripeCustomer.paymentMethods?.data?.length <= 0: undefined- const isOverFreeProjectLimit = (ui.profile?.total_free_projects ?? 0) >= 2+ const isOverFreeProjectLimit = totalFreeProjects >= freeProjectsLimitconst isInvalidSlug = isUndefined(currentOrg)const isSelectFreeTier = dbPricingPlan === PRICING_PLANS.FREE+ const canCreateProject =+ currentOrg?.is_owner &&+ (!isSelectFreeTier || (isSelectFreeTier && !isOverFreeProjectLimit && !isEmptyPaymentMethod))+const canSubmit =projectName != '' &&passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH &&dbRegion != '' &&dbPricingPlan != ''+const passwordErrorMessage =dbPass != '' && passwordStrengthScore < DEFAULT_MINIMUM_PASSWORD_STRENGTH? 'You need a stronger password'@@ -241,6 +251,7 @@ export const Wizard = observer(() => {label="Organization"layout="horizontal"value={currentOrg?.slug}+ // [Joshen] Should we use router.push?onChange={(slug) => (window.location.href = `/new/${slug}`)}>{organizations.map((x: any) => (@@ -254,131 +265,162 @@ export const Wizard = observer(() => {</Listbox.Option>))}</Listbox>++ {!currentOrg?.is_owner ? (+ <NotOrganizationOwnerWarning />+ ) : (+ <>+ {!isSelectFreeTier && isOverFreeProjectLimit && <FreeProjectLimitWarning />}+ {!isSelectFreeTier && isEmptyPaymentMethod && (+ <EmptyPaymentMethodWarning stripeCustomerId={stripeCustomerId} />+ )}+ </>+ )}</Panel.Content>- <>- <Panel.Content className="Form section-block--body has-inputs-centered border-b border-t border-panel-border-interior-light dark:border-panel-border-interior-dark">- <FormField- // @ts-ignore- label="Name"- type="text"- placeholder="Project name"- value={projectName}- onChange={onProjectNameChange}- autoFocus- />- </Panel.Content>-- <Panel.Content className="Form section-block--body has-inputs-centered border-b border-panel-border-interior-light dark:border-panel-border-interior-dark">- <FormField- // @ts-ignore- label="Database Password"- type="password"- placeholder="Type in a strong password"- value={dbPass}- onChange={onDbPassChange}- description={- <>- {dbPass && (- <div- aria-valuemax={100}- aria-valuemin={0}- aria-valuenow={(PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]}- aria-valuetext={- (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]+ {canCreateProject && (+ <>+ <Panel.Content className="Form section-block--body has-inputs-centered border-b border-t border-panel-border-interior-light dark:border-panel-border-interior-dark">+ <FormField+ // @ts-ignore+ label="Name"+ type="text"+ placeholder="Project name"+ value={projectName}+ onChange={onProjectNameChange}+ autoFocus+ />+ </Panel.Content>++ <Panel.Content className="Form section-block--body has-inputs-centered border-b border-panel-border-interior-light dark:border-panel-border-interior-dark">+ <FormField+ // @ts-ignore+ label="Database Password"+ type="password"+ placeholder="Type in a strong password"+ value={dbPass}+ onChange={onDbPassChange}+ description={+ <>+ {dbPass && (+ <div+ aria-valuemax={100}+ aria-valuemin={0}+ aria-valuenow={+ (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]+ }+ aria-valuetext={+ (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]+ }+ role="progressbar"+ className="mb-2 bg-bg-alt-light dark:bg-bg-alt-dark rounded overflow-hidden transition-all border dark:border-dark"+ >+ <div+ style={{+ width: (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore],+ }}+ className={`relative h-2 w-full ${+ (PASSWORD_STRENGTH_COLOR as any)[passwordStrengthScore]+ } transition-all duration-500 ease-out shadow-inner`}+ ></div>+ </div>+ )}+ <span+ className={+ passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH+ ? 'text-green-600'+ : ''}- role="progressbar"- className="mb-2 bg-bg-alt-light dark:bg-bg-alt-dark rounded overflow-hidden transition-all border dark:border-dark">- <div- style={{- width: (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore],- }}- className={`relative h-2 w-full ${- (PASSWORD_STRENGTH_COLOR as any)[passwordStrengthScore]- } transition-all duration-500 ease-out shadow-inner`}- ></div>- </div>- )}- <span- className={- passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH- ? 'text-green-600'- : ''- }+ {passwordStrengthMessage+ ? passwordStrengthMessage+ : 'This is the password to your postgres database, so it must be a strong password and hard to guess.'}+ </span>+ </>+ }+ errorMessage={+ passwordStrengthWarning+ ? `${passwordStrengthWarning}. ${passwordErrorMessage}.`+ : passwordErrorMessage+ }+ />+ </Panel.Content>++ <Panel.Content className="Form section-block--body has-inputs-centered border-b border-panel-border-interior-light dark:border-panel-border-interior-dark">+ <FormField+ // @ts-ignore+ label="Region"+ type="select"+ choices={REGIONS}+ value={dbRegion}+ onChange={onDbRegionChange}+ description="Select a region close to you for the best performance."+ />+ </Panel.Content>++ <Panel.Content className="Form section-block--body has-inputs-centered ">+ <Listbox+ label="Pricing Plan"+ layout="horizontal"+ value={dbPricingPlan}+ onChange={onDbPricingPlanChange}+ // @ts-ignore+ descriptionText={+ <>+ Select a plan that suits your needs. + <a className="underline" target="_blank" href="https://supabase.com/pricing">+ More details+ </a>+ </>+ }+ >+ {Object.entries(PRICING_PLANS).map(([k, v]) => (+ <Listbox.Option+ key={k}+ label={v}+ value={v}+ addOnBefore={() => <IconDollarSign />}>- {passwordStrengthMessage- ? passwordStrengthMessage- : 'This is the password to your postgres database, so it must be a strong password and hard to guess.'}- </span>- </>- }- errorMessage={- passwordStrengthWarning- ? `${passwordStrengthWarning}. ${passwordErrorMessage}.`- : passwordErrorMessage- }- />- </Panel.Content>-- <Panel.Content className="Form section-block--body has-inputs-centered border-b border-panel-border-interior-light dark:border-panel-border-interior-dark">- <FormField- // @ts-ignore- label="Region"- type="select"- choices={REGIONS}- value={dbRegion}- onChange={onDbRegionChange}- description="Select a region close to you for the best performance."- />- </Panel.Content>-- <Panel.Content className="Form section-block--body has-inputs-centered ">- <Listbox- label="Pricing Plan"- layout="horizontal"- value={dbPricingPlan}- onChange={onDbPricingPlanChange}- // @ts-ignore- descriptionText={- <>- Select a plan that suits your needs. - <a className="underline" target="_blank" href="https://supabase.com/pricing">- More details- </a>- </>- }- >- {Object.entries(PRICING_PLANS).map(([k, v]) => (- <Listbox.Option- key={k}- label={v}- value={v}- addOnBefore={() => <IconDollarSign />}- >- {`${v}${- v === PRICING_PLANS.PRO- ? ' - $25/month'- : v === PRICING_PLANS.PAYG- ? ' - $25/month plus usage costs'- : ''- }`}- </Listbox.Option>- ))}- </Listbox>-- {!isSelectFreeTier && isOverFreeProjectLimit && <FreeProjectLimitWarning />}- {!isSelectFreeTier && isEmptyPaymentMethod && (- <EmptyPaymentMethodWarning stripeCustomerId={stripeCustomerId} />- )}- </Panel.Content>- </>+ {`${v}${+ v === PRICING_PLANS.PRO+ ? ' - $25/month'+ : v === PRICING_PLANS.PAYG+ ? ' - $25/month plus usage costs'+ : ''+ }`}+ </Listbox.Option>+ ))}+ </Listbox>+ </Panel.Content>+ </>+ )}</></Panel></WizardLayout>)})+const NotOrganizationOwnerWarning = () => {+ return (+ <div className="mt-4">+ <InformationBox+ icon={<IconAlertCircle className="text-white" size="large" strokeWidth={1.5} />}+ defaultVisibility={true}+ hideCollapse+ title="You do not have permission to create a project"+ description={+ <div className="space-y-3">+ <p className="text-sm leading-normal">+ Only the organization owner can create new projects. Contact your organizaton owner to+ create a new project for this organization.+ </p>+ </div>+ }+ />+ </div>+ )+}+const FreeProjectLimitWarning = () => {return (<div className="mt-4">diff --git a/studio/pages/project/[ref]/index.tsx b/studio/pages/project/[ref]/index.tsxindex cf6e38cecc5..f694cb0754b 100644--- a/studio/pages/project/[ref]/index.tsx+++ b/studio/pages/project/[ref]/index.tsx@@ -35,7 +35,7 @@ const Home: NextPage = () => {}const hasProjectData =- (usage && usage.bucketSize) || (usage && usage.authUsers !== '0') || (usage && usage.dbTables)+ usage && (usage?.bucketSize || (usage?.authUsers ?? '0') !== '0' || usage?.dbTables)? true: falsediff --git a/studio/pages/project/[ref]/settings/general.tsx b/studio/pages/project/[ref]/settings/general.tsxindex 3b8f330b4df..1f72cc3c688 100644--- a/studio/pages/project/[ref]/settings/general.tsx+++ b/studio/pages/project/[ref]/settings/general.tsx@@ -17,7 +17,7 @@ import {import { API_URL } from 'lib/constants'import { pluckJsonSchemaFields, pluckObjectFields } from 'lib/helpers'import { post, delete_ } from 'lib/common/fetch'-import { useStore, withAuth } from 'hooks'+import { useProfile, useStore, withAuth } from 'hooks'import { SettingsLayout } from 'components/layouts'import Panel from 'components/to-be-cleaned/Panel'import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'@@ -173,6 +173,7 @@ const GeneralSettings = observer(() => {const ProjectDeleteModal = ({ project }: any) => {const router = useRouter()+ const { mutateProfile } = useProfile()const { ui, app } = useStore()const [isOpen, setIsOpen] = useState(false)@@ -189,7 +190,7 @@ const ProjectDeleteModal = ({ project }: any) => {try {const response = await delete_(`${API_URL}/projects/${project.ref}/remove`)if (response.error) throw response.error- app.onProjectDeleted(response)+ app.onProjectDeleted(response, mutateProfile)ui.setNotification({ category: 'success', message: `Successfully deleted ${project.name}` })router.push(`/`)} catch (error: any) {diff --git a/studio/stores/UiStore.ts b/studio/stores/UiStore.tsindex 728a0a99171..55c59c0b381 100644--- a/studio/stores/UiStore.ts+++ b/studio/stores/UiStore.ts@@ -123,7 +123,7 @@ export default class UiStore implements IUiStore {}setProfile(value?: User) {- if (value && value?.id != this.profile?.id) {+ if (value && value?.id !== this.profile?.id) {Telemetry.sendIdentify(value)}diff --git a/studio/stores/app/AppStore.ts b/studio/stores/app/AppStore.tsindex e492f257b0d..b50a0bebfd0 100644--- a/studio/stores/app/AppStore.ts+++ b/studio/stores/app/AppStore.ts@@ -1,9 +1,8 @@-import { Dictionary } from '@supabase/grid'import { cloneDeep } from 'lodash'import { values } from 'mobx'import { Project } from 'types'-import { API_URL } from 'lib/constants'+import { API_URL, STRIPE_PRODUCT_IDS } from 'lib/constants'import { IRootStore } from '../RootStore'import DatabaseStore, { IDatabaseStore } from './DatabaseStore'import OrganizationStore from './OrganizationStore'@@ -14,7 +13,7 @@ export interface IAppStore {organizations: OrganizationStoredatabase: IDatabaseStoreonProjectUpdated: (project: any) => void- onProjectDeleted: (project: any) => void+ onProjectDeleted: (project: any, mutateProfile: Function) => voidonOrgAdded: (org: any) => voidonOrgUpdated: (org: any) => voidonOrgDeleted: (org: any) => void@@ -53,12 +52,22 @@ export default class AppStore implements IAppStore {}}- onProjectDeleted(project: any) {+ onProjectDeleted(project: any, mutateProfile: Function) {if (project && project.id) {+ const profile = this.rootStore.ui.profile+ const projectMetadata = this.projects.find((proj: any) => proj.id === project.id)+// cleanup project saved querieslocalStorage.removeItem(`supabase-queries-state-${project.ref}`)localStorage.removeItem(`supabase_${project.ref}`)delete this.projects.data[project.id]++ if (profile && projectMetadata?.subscription_tier_prod_id === STRIPE_PRODUCT_IDS.FREE) {+ mutateProfile({+ ...profile,+ total_free_projects: profile.total_free_projects - 1,+ })+ }}}diff --git a/studio/types/base.ts b/studio/types/base.tsindex d104cb4fe25..08799a0c9c0 100644--- a/studio/types/base.ts+++ b/studio/types/base.ts@@ -6,6 +6,7 @@ export interface Organization {project_limit: numberstripe_customer_id?: stringtotal_free_projects?: number+ is_owner?: boolean}export interface Project {@@ -18,6 +19,8 @@ export interface Project {region: stringconnectionString: stringinserted_at: string+ subscription_tier: string+ subscription_tier_prod_id: string}export interface User {@@ -28,7 +31,8 @@ export interface User {first_name: stringlast_name: stringis_alpha_user: boolean- total_free_projects?: number+ free_project_limit: number+ total_free_projects: number}export interface Member {