The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Project Level Permissions (#27347)
Joshen Lim1127c4ba8810
diff --git a/apps/studio/components/grid/components/header/RefreshButton.tsx b/apps/studio/components/grid/components/header/RefreshButton.tsxindex 97ae14c67d1..9c557e2b43c 100644--- a/apps/studio/components/grid/components/header/RefreshButton.tsx+++ b/apps/studio/components/grid/components/header/RefreshButton.tsx@@ -1,12 +1,11 @@import { useQueryClient } from '@tanstack/react-query'-import { useParams } from 'common/hooks'+import { RefreshCw } from 'lucide-react'++import { useParams } from 'common'import type { SupaTable } from 'components/grid/types'import { sqlKeys } from 'data/sql/keys'-import { useEffect, useState } from 'react'-import { Button, IconCheck, IconRefreshCw } from 'ui'-import { SupabaseGridQueue } from '../../queue'import type { TableLike } from 'hooks/misc/useTable'-import { Check, RefreshCw } from 'lucide-react'+import { Button } from 'ui'export type RefreshButtonProps = {table: TableLike | SupaTable@@ -16,31 +15,7 @@ export type RefreshButtonProps = {const RefreshButton = ({ table, isRefetching }: RefreshButtonProps) => {const { ref } = useParams()const queryClient = useQueryClient()-const queryKey = sqlKeys.query(ref, [table.schema, table.name])- const [status, setStatus] = useState<string>()-- useEffect(() => {- let isMounted = true- let timer: number | null-- SupabaseGridQueue.on('active', () => {- if (timer) clearTimeout(timer)-- if (isMounted) setStatus('saving')- })- SupabaseGridQueue.on('idle', () => {- if (timer) clearTimeout(timer)- timer = window.setTimeout(() => setStatus(undefined), 2000)-- if (isMounted) setStatus('saved')- })-- return () => {- isMounted = false- if (timer) clearTimeout(timer)- }- }, [])async function onClick() {await queryClient.invalidateQueries(queryKey)@@ -49,21 +24,11 @@ const RefreshButton = ({ table, isRefetching }: RefreshButtonProps) => {return (<Buttontype="text"- icon={- !status ? (- <RefreshCw className="text-foreground-muted" strokeWidth={1.5} />- ) : status === 'saved' ? (- <Check className="text-brand" strokeWidth={3} />- ) : (- <></>- )- }- onClick={() => {- if (!status) onClick()- }}- loading={isRefetching || status === 'saving'}+ loading={isRefetching}+ icon={<RefreshCw className="text-foreground-muted" strokeWidth={1.5} />}+ onClick={() => onClick()}>- {!status ? 'Refresh' : status === 'saved' ? 'Changes saved' : 'Saving changes'}+ Refresh</Button>)}diff --git a/apps/studio/components/grid/queue.ts b/apps/studio/components/grid/queue.tsdeleted file mode 100644index 0eaa984d86c..00000000000--- a/apps/studio/components/grid/queue.ts+++ /dev/null@@ -1,3 +0,0 @@-import PQueue from 'p-queue'--export const SupabaseGridQueue = new PQueue({ concurrency: 1 })diff --git a/apps/studio/components/interfaces/Account/Preferences/AccountInformation.tsx b/apps/studio/components/interfaces/Account/Preferences/AccountInformation.tsxindex 8bc199d8904..e550a91ada0 100644--- a/apps/studio/components/interfaces/Account/Preferences/AccountInformation.tsx+++ b/apps/studio/components/interfaces/Account/Preferences/AccountInformation.tsx@@ -106,7 +106,7 @@ const AccountInformation = ({ profile }: { profile?: Profile }) => {<p className="text-foreground-light break-all">Password</p></div><div className="col-span-8">- <Button asChild type="default" size="medium">+ <Button asChild type="default"><Link href="/reset-password">Reset password</Link></Button></div>diff --git a/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx b/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsxindex 5643674bc62..127da3dc3b8 100644--- a/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx+++ b/apps/studio/components/interfaces/Account/Preferences/ProfileInformation.tsx@@ -32,7 +32,10 @@ export const ProfileInformation = ({ profile }: { profile: Profile }) => {})const { mutate: updateProfile, isLoading } = useProfileUpdateMutation({- onSuccess: () => toast.success('Successfully saved profile'),+ onSuccess: (data) => {+ toast.success('Successfully saved profile')+ form.reset({ first_name: data.first_name, last_name: data.last_name })+ },onError: (error) => toast.error(`Failed to update profile: ${error.message}`),})diff --git a/apps/studio/components/interfaces/Account/TOTPFactors/AddNewFactorModal.tsx b/apps/studio/components/interfaces/Account/TOTPFactors/AddNewFactorModal.tsxindex c425c0276c2..555e03f3391 100644--- a/apps/studio/components/interfaces/Account/TOTPFactors/AddNewFactorModal.tsx+++ b/apps/studio/components/interfaces/Account/TOTPFactors/AddNewFactorModal.tsx@@ -77,14 +77,12 @@ const FirstStep = ({ visible, name, enroll, setName, isEnrolling, onClose }: Fir})}}>- <div className="pt-6 pb-5">- <Input- label="Provide a name to identify this app"- descriptionText="A string will be randomly generated if a name is not provided"- value={name}- onChange={(e) => setName(e.target.value)}- />- </div>+ <Input+ label="Provide a name to identify this app"+ descriptionText="A string will be randomly generated if a name is not provided"+ value={name}+ onChange={(e) => setName(e.target.value)}+ /></ConfirmationModal>)}diff --git a/apps/studio/components/interfaces/Auth/AdvancedAuthSettingsForm/AdvancedAuthSettingsForm.tsx b/apps/studio/components/interfaces/Auth/AdvancedAuthSettingsForm/AdvancedAuthSettingsForm.tsxindex a2f90983896..0dfcaa60436 100644--- a/apps/studio/components/interfaces/Auth/AdvancedAuthSettingsForm/AdvancedAuthSettingsForm.tsx+++ b/apps/studio/components/interfaces/Auth/AdvancedAuthSettingsForm/AdvancedAuthSettingsForm.tsx@@ -12,6 +12,7 @@ import {FormSectionContent,FormSectionLabel,} from 'components/ui/Forms'+import NoPermission from 'components/ui/NoPermission'import UpgradeToPro from 'components/ui/UpgradeToPro'import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'@@ -59,6 +60,7 @@ const AdvancedAuthSettingsForm = () => {const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()const formId = 'auth-config-advanced-form'+ const canReadConfig = useCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')const organization = useSelectedOrganization()@@ -112,6 +114,10 @@ const AdvancedAuthSettingsForm = () => {)}+ if (!canReadConfig) {+ return <NoPermission resourceText="view auth configuration settings" />+ }+return (<Form id={formId} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>{({ handleReset, resetForm, values, initialValues }: any) => {diff --git a/apps/studio/components/interfaces/Auth/AuthProvidersForm/AuthProvidersForm.tsx b/apps/studio/components/interfaces/Auth/AuthProvidersForm/AuthProvidersForm.tsxindex 2ac9bfd9095..5b713c3e610 100644--- a/apps/studio/components/interfaces/Auth/AuthProvidersForm/AuthProvidersForm.tsx+++ b/apps/studio/components/interfaces/Auth/AuthProvidersForm/AuthProvidersForm.tsx@@ -1,20 +1,15 @@+import { ExternalLink } from 'lucide-react'+import Link from 'next/link'+import { useParams } from 'common'import { FormHeader } from 'components/ui/Forms'import { HorizontalShimmerWithIcon } from 'components/ui/Shimmers'import { useAuthConfigQuery } from 'data/auth/auth-config-query'-import {- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Button,- IconAlertCircle,-} from 'ui'+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'import { PROVIDERS_SCHEMAS } from '../AuthProvidersFormValidation'import { ProviderCollapsibleClasses } from './AuthProvidersForm.constants'import ProviderForm from './ProviderForm'-import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'-import Link from 'next/link'-import { ExternalLink } from 'lucide-react'const AuthProvidersForm = () => {const { ref: projectRef } = useParams()@@ -67,7 +62,7 @@ const AuthProvidersForm = () => {))}{isError && (<Alert_Shadcn_ variant="destructive">- <IconAlertCircle strokeWidth={2} />+ <WarningIcon /><AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_><AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_></Alert_Shadcn_>diff --git a/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx b/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsxindex 9679aa0a811..6a656c4c7c0 100644--- a/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx+++ b/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx@@ -1,17 +1,18 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { useState } from 'react'import toast from 'react-hot-toast'import ReactMarkdown from 'react-markdown'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import type { components } from 'data/api'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'import { useProjectApiQuery } from 'data/config/project-api-query'import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'import { useCheckPermissions } from 'hooks'import { BASE_PATH } from 'lib/constants'-import { Alert, Button, Collapsible, Form, IconCheck, IconChevronUp, Input } from 'ui'+import { Check, ChevronUp } from 'lucide-react'+import { Alert, Button, Collapsible, Form, Input } from 'ui'import { ProviderCollapsibleClasses } from './AuthProvidersForm.constants'import type { Provider } from './AuthProvidersForm.types'import FormField from './FormField'@@ -110,7 +111,7 @@ const ProviderForm = ({ config, provider }: ProviderFormProps) => {className="group flex w-full items-center justify-between rounded py-3 px-6 text-foreground"><div className="flex items-center gap-3">- <IconChevronUp+ <ChevronUpclassName="text-border-stronger transition data-open-parent:rotate-0 data-closed-parent:rotate-180"strokeWidth={2}width={14}@@ -126,7 +127,7 @@ const ProviderForm = ({ config, provider }: ProviderFormProps) => {{isActive ? (<div className="flex items-center gap-1 rounded-full border border-brand-400 bg-brand-200 py-1 px-1 text-xs text-brand"><span className="rounded-full bg-brand p-0.5 text-xs text-brand-200">- <IconCheck strokeWidth={2} size={12} />+ <Check strokeWidth={2} size={12} /></span><span className="px-1">Enabled</span></div>@@ -203,34 +204,21 @@ const ProviderForm = ({ config, provider }: ProviderFormProps) => {>Cancel</Button>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger type="button">- <Button- htmlType="submit"- loading={isUpdatingConfig}- disabled={isUpdatingConfig || !canUpdateConfig || noChanges}- >- Save- </Button>- </Tooltip.Trigger>- {!canUpdateConfig && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to update provider settings- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ htmlType="submit"+ loading={isUpdatingConfig}+ disabled={isUpdatingConfig || !canUpdateConfig || noChanges}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canUpdateConfig+ ? 'You need additional permissions to update provider settings'+ : undefined,+ },+ }}+ >+ Save+ </ButtonTooltip></div></div></div>diff --git a/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsx b/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsxindex 93cf712bc18..68fa1bff029 100644--- a/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsx+++ b/apps/studio/components/interfaces/Auth/BasicAuthSettingsForm/BasicAuthSettingsForm.tsx@@ -1,5 +1,5 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { ExternalLink } from 'lucide-react'+import { ExternalLink, Eye, EyeOff } from 'lucide-react'import Link from 'next/link'import { useEffect, useState } from 'react'import toast from 'react-hot-toast'@@ -14,6 +14,7 @@ import {FormSectionContent,FormSectionLabel,} from 'components/ui/Forms'+import NoPermission from 'components/ui/NoPermission'import UpgradeToPro from 'components/ui/UpgradeToPro'import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'@@ -26,9 +27,6 @@ import {Alert_Shadcn_,Button,Form,- IconAlertCircle,- IconEye,- IconEyeOff,Input,InputNumber,Toggle,@@ -91,6 +89,7 @@ const BasicAuthSettingsForm = () => {const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()const [hidden, setHidden] = useState(true)+ const canReadConfig = useCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')const organization = useSelectedOrganization()@@ -146,13 +145,17 @@ const BasicAuthSettingsForm = () => {if (isError) {return (<Alert_Shadcn_ variant="destructive">- <IconAlertCircle strokeWidth={2} />+ <WarningIcon /><AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_><AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_></Alert_Shadcn_>)}+ if (!canReadConfig) {+ return <NoPermission resourceText="view auth configuration settings" />+ }+return (<Form id={formId} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>{({ handleReset, resetForm, values, initialValues }: any) => {@@ -434,7 +437,7 @@ const BasicAuthSettingsForm = () => {disabled={!canUpdateConfig}actions={<Button- icon={hidden ? <IconEye /> : <IconEyeOff />}+ icon={hidden ? <Eye /> : <EyeOff />}type="default"onClick={() => setHidden(!hidden)}/>diff --git a/apps/studio/components/interfaces/Auth/Hooks/AddHookDropdown.tsx b/apps/studio/components/interfaces/Auth/Hooks/AddHookDropdown.tsxindex 05de44ca4d1..d28de45d2b9 100644--- a/apps/studio/components/interfaces/Auth/Hooks/AddHookDropdown.tsx+++ b/apps/studio/components/interfaces/Auth/Hooks/AddHookDropdown.tsx@@ -1,4 +1,5 @@import { ChevronDown } from 'lucide-react'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { useAuthConfigQuery } from 'data/auth/auth-config-query'@@ -10,12 +11,16 @@ import {DropdownMenuLabel,DropdownMenuSeparator,DropdownMenuTrigger,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'import { HOOKS_DEFINITIONS, HOOK_DEFINITION_TITLE, Hook } from './hooks.constants'import { extractMethod, isValidHook } from './hooks.utils'-import { useSelectedOrganization } from 'hooks'+import { useCheckPermissions, useSelectedOrganization } from 'hooks'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import { IS_PLATFORM } from 'lib/constants'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'interface AddHookDropdownProps {buttonText?: string@@ -33,7 +38,8 @@ export const AddHookDropdown = ({{ orgSlug: organization?.slug },{ enabled: IS_PLATFORM })- const { data: authConfig, error: authConfigError, isError } = useAuthConfigQuery({ projectRef })+ const { data: authConfig } = useAuthConfigQuery({ projectRef })+ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')const hooks: Hook[] = HOOKS_DEFINITIONS.map((definition) => {return {@@ -49,6 +55,20 @@ export const AddHookDropdown = ({const nonEnterpriseHookOptions = hooks.filter((h) => !isValidHook(h) && !h.enterprise)const enterpriseHookOptions = hooks.filter((h) => !isValidHook(h) && h.enterprise)+ if (!canUpdateConfig) {+ return (+ <ButtonTooltip+ disabled+ type="primary"+ tooltip={{+ content: { side: 'bottom', text: 'You need additional permissions to add auth hooks' },+ }}+ >+ {buttonText}+ </ButtonTooltip>+ )+ }+return (<DropdownMenu modal={false}><DropdownMenuTrigger asChild>diff --git a/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx b/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsxindex e5fdbe8fe51..b38c0f43d84 100644--- a/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx+++ b/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx@@ -1,5 +1,6 @@+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { Check, Webhook } from 'lucide-react'-import { Badge, Button, Input } from 'ui'+import { Badge, Input } from 'ui'import { Hook } from './hooks.constants'interface HookCardProps {@@ -84,21 +85,31 @@ export const HookCard = ({ hook, canUpdateConfig, onToggle, onSelect }: HookCard)}</div><div className="flex flex-row gap-2">- <Button type="default" disabled={!canUpdateConfig} onClick={() => onSelect()}>+ <ButtonTooltip+ type="default"+ disabled={!canUpdateConfig}+ onClick={() => onSelect()}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to configure auth hooks',+ },+ }}+ >Configure hook- </Button>+ </ButtonTooltip></div></div><div className="flex-1">{hook.enabled ? (- <Badge className="space-x-1" size="large" variant="brand">+ <Badge className="space-x-1" variant="brand"><div className="h-3.5 w-3.5 bg-brand rounded-full flex justify-center items-center"><Check className="h-2 w-2 text-background-overlay " strokeWidth={6} /></div><span>Enabled</span></Badge>) : (- <Badge variant="warning" size="large">+ <Badge variant="warning"><span>Disabled</span></Badge>)}diff --git a/apps/studio/components/interfaces/Auth/RateLimits/RateLimits.tsx b/apps/studio/components/interfaces/Auth/RateLimits/RateLimits.tsxindex fa189b7e79a..85e7c15ba9b 100644--- a/apps/studio/components/interfaces/Auth/RateLimits/RateLimits.tsx+++ b/apps/studio/components/interfaces/Auth/RateLimits/RateLimits.tsx@@ -175,9 +175,13 @@ const RateLimits = () => {control={form.control}name="RATE_LIMIT_EMAIL_SENT"render={({ field }) => (- <FormItem_Shadcn_>+ <FormItem_Shadcn_ className="flex flex-col gap-y-2"><FormControl_Shadcn_>- <Input_Shadcn_ disabled={!canUpdateEmailLimit} type="number" {...field} />+ <Input_Shadcn_+ disabled={!canUpdateConfig || !canUpdateEmailLimit}+ type="number"+ {...field}+ /></FormControl_Shadcn_>{!authConfig.EXTERNAL_EMAIL_ENABLED ? (<Alert_Shadcn_>@@ -240,10 +244,10 @@ const RateLimits = () => {control={form.control}name="RATE_LIMIT_SMS_SENT"render={({ field }) => (- <FormItem_Shadcn_>+ <FormItem_Shadcn_ className="flex flex-col gap-y-2"><FormControl_Shadcn_><Input_Shadcn_- disabled={!canUpdateSMSRateLimit}+ disabled={!canUpdateConfig || !canUpdateSMSRateLimit}type="number"{...field}/>@@ -294,7 +298,7 @@ const RateLimits = () => {render={({ field }) => (<FormItem_Shadcn_><FormControl_Shadcn_>- <Input_Shadcn_ type="number" {...field} />+ <Input_Shadcn_ type="number" {...field} disabled={!canUpdateConfig} /></FormControl_Shadcn_>{field.value > 0 && (<>@@ -331,7 +335,7 @@ const RateLimits = () => {render={({ field }) => (<FormItem_Shadcn_><FormControl_Shadcn_>- <Input_Shadcn_ type="number" {...field} />+ <Input_Shadcn_ type="number" {...field} disabled={!canUpdateConfig} /></FormControl_Shadcn_>{field.value > 0 && (<p className="text-foreground-lighter text-sm">@@ -363,10 +367,10 @@ const RateLimits = () => {control={form.control}name="RATE_LIMIT_ANONYMOUS_USERS"render={({ field }) => (- <FormItem_Shadcn_>+ <FormItem_Shadcn_ className="flex flex-col gap-y-2"><FormControl_Shadcn_><Input_Shadcn_- disabled={!canUpdateAnonymousUsersRateLimit}+ disabled={!canUpdateConfig || !canUpdateAnonymousUsersRateLimit}type="number"{...field}/>diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsxindex 7af2c9aa27b..ccf58450f56 100644--- a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx@@ -1,6 +1,6 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'+import { ExternalLink } from 'lucide-react'import Link from 'next/link'import { useMemo, useState } from 'react'import toast from 'react-hot-toast'@@ -11,18 +11,18 @@ import {Button,DialogSectionSeparator,Form,- IconAlertCircle,- IconExternalLink,Input,Modal,} from 'ui'import { object, string } from 'yup'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { FormHeader } from 'components/ui/Forms'import { HorizontalShimmerWithIcon } from 'components/ui/Shimmers'import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'import { useCheckPermissions } from 'hooks'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'import { urlRegex } from '../Auth.constants'import RedirectUrlList from './RedirectUrlList'import ValueContainer from './ValueContainer'@@ -110,7 +110,7 @@ const RedirectUrls = () => {description={`URLs that auth providers are permitted to redirect to post authentication. Wildcards are allowed, for example, https://*.domain.com`}/><div className="flex items-center gap-2 mb-6 ml-12">- <Button asChild type="default" icon={<IconExternalLink />}>+ <Button asChild type="default" icon={<ExternalLink />}><Linkhref="https://supabase.com/docs/guides/auth/concepts/redirect-urls"target="_blank"@@ -119,30 +119,18 @@ const RedirectUrls = () => {Documentation</Link></Button>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button disabled={!canUpdateConfig} onClick={() => setOpen(true)}>- Add URL- </Button>- </Tooltip.Trigger>- {!canUpdateConfig && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to update redirect URLs- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ disabled={!canUpdateConfig}+ onClick={() => setOpen(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to update redirect URLs',+ },+ }}+ >+ Add URL+ </ButtonTooltip></div></div>{isLoading && (@@ -157,7 +145,7 @@ const RedirectUrls = () => {)}{isError && (<Alert_Shadcn_ variant="destructive">- <IconAlertCircle strokeWidth={2} />+ <WarningIcon /><AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_><AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_></Alert_Shadcn_>@@ -212,7 +200,7 @@ const RedirectUrls = () => {hideFootersize="small"visible={selectedUrlToDelete !== undefined}- header={<h3 className="text-sm">Remove URL</h3>}+ header="Remove URL"onCancel={() => setSelectedUrlToDelete(undefined)}><Modal.Content>@@ -225,7 +213,7 @@ const RedirectUrls = () => {</p></Modal.Content><Modal.Separator />- <Modal.Content>+ <Modal.Content className="flex items-center gap-x-2"><Buttonblocktype="default"diff --git a/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx b/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsxindex 0299a71e1cb..2139209da12 100644--- a/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx+++ b/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx@@ -34,6 +34,8 @@ import EmailRateLimitsAlert from '../EmailRateLimitsAlert'import { urlRegex } from './../Auth.constants'import { defaultDisabledSmtpFormValues } from './SmtpForm.constants'import { generateFormValues, isSmtpEnabled } from './SmtpForm.utils'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'+import NoPermission from 'components/ui/NoPermission'const SmtpForm = () => {const { ref: projectRef } = useParams()@@ -51,6 +53,7 @@ const SmtpForm = () => {const formId = 'auth-config-smtp-form'const initialValues = generateFormValues(authConfig)+ const canReadConfig = useCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')useEffect(() => {@@ -148,13 +151,17 @@ const SmtpForm = () => {if (isError) {return (<Alert_Shadcn_ variant="destructive">- <IconAlertCircle strokeWidth={2} />+ <WarningIcon /><AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_><AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_></Alert_Shadcn_>)}+ if (!canReadConfig) {+ return <NoPermission resourceText="view SMTP settings" />+ }+return (<Form id={formId} initialValues={initialValues} onSubmit={onSubmit} validationSchema={schema}>{({ resetForm, values }: any) => {diff --git a/apps/studio/components/interfaces/Auth/Users/AddUserDropdown.tsx b/apps/studio/components/interfaces/Auth/Users/AddUserDropdown.tsxindex 1bf095ff73a..d5c41edbc55 100644--- a/apps/studio/components/interfaces/Auth/Users/AddUserDropdown.tsx+++ b/apps/studio/components/interfaces/Auth/Users/AddUserDropdown.tsx@@ -1,22 +1,22 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { ChevronDown, Mail, UserPlus } from 'lucide-react'import { useState } from 'react'import semver from 'semver'++import { useCheckPermissions } from 'hooks'+import { IS_PLATFORM } from 'lib/constants'import {Button,DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,- IconChevronDown,- IconMail,- IconUserPlus,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'--import { useCheckPermissions } from 'hooks'-import { IS_PLATFORM } from 'lib/constants'-import InviteUserModal from './InviteUserModal'import CreateUserModal from './CreateUserModal'+import InviteUserModal from './InviteUserModal'export type AddUserDropdownProps = {projectKpsVersion?: string@@ -41,73 +41,52 @@ const AddUserDropdown = ({ projectKpsVersion }: AddUserDropdownProps) => {<><DropdownMenu><DropdownMenuTrigger asChild>- <Button type="primary" iconRight={<IconChevronDown strokeWidth={1.5} />}>+ <Button type="primary" iconRight={<ChevronDown size={14} strokeWidth={1.5} />}>Add user</Button></DropdownMenuTrigger><DropdownMenuContent side="bottom" align="end">{inviteEnabled && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full">+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild><DropdownMenuItem- className="space-x-2"+ className="space-x-2 !pointer-events-auto"disabled={!canInviteUsers}- onClick={() => setInviteVisible(true)}+ onClick={() => {+ if (canInviteUsers) setInviteVisible(true)+ }}>- <IconMail size="small" />+ <Mail size={14} /><p>Send invitation</p></DropdownMenuItem>- </Tooltip.Trigger>+ </TooltipTrigger_Shadcn_>{!canInviteUsers && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to invite users- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to invite users+ </TooltipContent_Shadcn_>)}- </Tooltip.Root>+ </Tooltip_Shadcn_>)}- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full text-left">+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild><DropdownMenuItem- className="space-x-2"+ className="space-x-2 !pointer-events-auto"disabled={!canCreateUsers}- onClick={() => setCreateVisible(true)}+ onClick={() => {+ if (canCreateUsers) setCreateVisible(true)+ }}>- <IconUserPlus size="small" />+ <UserPlus size={14} /><p>Create new user</p></DropdownMenuItem>- </Tooltip.Trigger>-+ </TooltipTrigger_Shadcn_>{!canCreateUsers && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to create users- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to create users+ </TooltipContent_Shadcn_>)}- </Tooltip.Root>+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu>diff --git a/apps/studio/components/interfaces/Auth/Users/UserDropdown.tsx b/apps/studio/components/interfaces/Auth/Users/UserDropdown.tsxindex 1c576066396..a60c347e596 100644--- a/apps/studio/components/interfaces/Auth/Users/UserDropdown.tsx+++ b/apps/studio/components/interfaces/Auth/Users/UserDropdown.tsx@@ -1,8 +1,8 @@-import * as Tooltip from '@radix-ui/react-tooltip'-import { useParams } from 'common'+import { Mail, MoreHorizontal, ShieldOff, Trash, User as UserIcon } from 'lucide-react'import { useState } from 'react'import toast from 'react-hot-toast'+import { useParams } from 'common'import { useUserDeleteMFAFactorsMutation } from 'data/auth/user-delete-mfa-factors-mutation'import { useUserDeleteMutation } from 'data/auth/user-delete-mutation'import { useUserResetPasswordMutation } from 'data/auth/user-reset-password-mutation'@@ -12,32 +12,33 @@ import type { User } from 'data/auth/users-query'import { timeout } from 'lib/helpers'import {Button,- cn,DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,- IconMail,- IconMoreVertical,- IconShieldOff,- IconTrash,- IconUser,+ Tooltip_Shadcn_,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,} from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'interface UserDropdownProps {user: User- canRemoveUser: boolean- canRemoveMFAFactors: boolean+ permissions: {+ canRemoveUser: boolean+ canRemoveMFAFactors: boolean+ canSendMagicLink: boolean+ canSendRecovery: boolean+ canSendOtp: boolean+ }setSelectedUser: (user: User) => voidsetUserSidePanelOpen: (open: boolean) => void}const UserDropdown = ({user,- canRemoveUser,- canRemoveMFAFactors,+ permissions,setSelectedUser,setUserSidePanelOpen,}: UserDropdownProps) => {@@ -45,6 +46,9 @@ const UserDropdown = ({const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)const [isDeleteFactorsModalOpen, setIsDeleteFactorsModalOpen] = useState(false)+ const { canRemoveUser, canRemoveMFAFactors, canSendMagicLink, canSendRecovery, canSendOtp } =+ permissions+const { mutate: resetPassword, isLoading: isResetting } = useUserResetPasswordMutation({onSuccess: () => {toast.success(`Sent password recovery to ${user.email}`)@@ -113,103 +117,119 @@ const UserDropdown = ({<><DropdownMenu><DropdownMenuTrigger asChild>- <Button type="text" loading={isLoading} className="hover:border-muted flex">- <IconMoreVertical />- </Button>+ <Button type="text" loading={isLoading} className="px-1.5" icon={<MoreHorizontal />} /></DropdownMenuTrigger><DropdownMenuContent><><DropdownMenuItem className="space-x-2" onClick={handleViewUserInfo}>- <IconUser size="tiny" />+ <UserIcon size={14} /><p>View user info</p></DropdownMenuItem><DropdownMenuSeparator />{user.email !== null ? (<>- <DropdownMenuItem className="space-x-2" onClick={handleResetPassword}>- <IconMail size="tiny" />- <p>Send password recovery</p>- </DropdownMenuItem>- <DropdownMenuItem className="space-x-2" onClick={handleSendMagicLink}>- <IconMail size="tiny" />- <p>Send magic link</p>- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ className="space-x-2 !pointer-events-auto"+ disabled={!canSendRecovery}+ onClick={() => {+ if (canSendRecovery) handleResetPassword()+ }}+ >+ <Mail size={14} />+ <p>Send password recovery</p>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canSendRecovery && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to send password recovery.+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ disabled={!canSendMagicLink}+ className="space-x-2 !pointer-events-auto"+ onClick={() => {+ if (canSendMagicLink) handleSendMagicLink()+ }}+ >+ <Mail size={14} />+ <p>Send magic link</p>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canSendMagicLink && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to send magic link+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_></>) : null}{user.phone !== null ? (- <DropdownMenuItem className="space-x-2" onClick={handleSendOtp}>- <IconMail size="tiny" />- <p>Send OTP</p>- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ disabled={!canSendOtp}+ className="space-x-2 !pointer-events-auto"+ onClick={() => {+ if (canSendOtp) handleSendOtp()+ }}+ >+ <Mail size={14} />+ <p>Send OTP</p>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canSendOtp && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to send OTP+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_>) : null}<DropdownMenuSeparator />- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild><DropdownMenuItemonClick={() => {- setIsDeleteFactorsModalOpen(true)+ if (canRemoveMFAFactors) setIsDeleteFactorsModalOpen(true)}}disabled={!canRemoveMFAFactors}- className="space-x-2"+ className="space-x-2 !pointer-events-auto">- <IconShieldOff size="tiny" />+ <ShieldOff size={14} /><p>Remove MFA factors</p></DropdownMenuItem>- </Tooltip.Trigger>- {/*- [Joshen] Deleting MFA factors should be different ABAC perms i think- need to double check with KM / anyone familiar with ABAC- */}+ </TooltipTrigger_Shadcn_>{!canRemoveMFAFactors && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to remove a user's authentication factors.- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to remove a user's authentication factors+ </TooltipContent_Shadcn_>)}- </Tooltip.Root>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>+ </Tooltip_Shadcn_>++ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild><DropdownMenuItem+ disabled={!canRemoveUser}onClick={() => {- setIsDeleteModalOpen(true)+ if (canRemoveUser) setIsDeleteModalOpen(true)}}- disabled={!canRemoveUser}- className="space-x-2"+ className="space-x-2 !pointer-events-auto">- <IconTrash size="tiny" />+ <Trash size={14} /><p>Delete user</p></DropdownMenuItem>- </Tooltip.Trigger>+ </TooltipTrigger_Shadcn_>{!canRemoveUser && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={cn([- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ])}- >- <span className="text-xs text-foreground">- You need additional permissions to delete users- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to delete users+ </TooltipContent_Shadcn_>)}- </Tooltip.Root>+ </Tooltip_Shadcn_></></DropdownMenuContent></DropdownMenu>diff --git a/apps/studio/components/interfaces/Auth/Users/UsersList.tsx b/apps/studio/components/interfaces/Auth/Users/UsersList.tsxindex 863684be636..64949ecb3b3 100644--- a/apps/studio/components/interfaces/Auth/Users/UsersList.tsx+++ b/apps/studio/components/interfaces/Auth/Users/UsersList.tsx@@ -4,13 +4,13 @@ import Table from 'components/to-be-cleaned/Table'import AlertError from 'components/ui/AlertError'import type { User } from 'data/auth/users-query'import { useCheckPermissions } from 'hooks'+import { AlertCircle } from 'lucide-react'+import { useState } from 'react'import type { ResponseError } from 'types'-import { IconAlertCircle } from 'ui'+import UsersSidePanel from './UserSidePanel'import UserListItem from './UsersListItem'import UsersListItemSkeleton from './UsersListItemSkeleton'import UsersPagination from './UsersPagination'-import UsersSidePanel from './UserSidePanel'-import { useState } from 'react'interface UsersListProps {page: number@@ -39,6 +39,9 @@ const UsersList = ({const [userSidePanelOpen, setUserSidePanelOpen] = useState(false)// Check once on the top level, rather than checking for every row+ const canSendMagicLink = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_magic_link')+ const canSendRecovery = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_recovery')+ const canSendOtp = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_otp')const canRemoveUser = useCheckPermissions(PermissionAction.TENANT_SQL_DELETE, 'auth.users')const canRemoveMFAFactors = useCheckPermissions(PermissionAction.TENANT_SQL_DELETE,@@ -77,7 +80,7 @@ const UsersList = ({className="h-14 whitespace-nowrap border-t p-4 text-sm leading-5 text-gray-300"><div className="flex items-center space-x-3 opacity-75">- <IconAlertCircle size={16} strokeWidth={2} />+ <AlertCircle size={16} strokeWidth={2} /><p className="text-foreground-light">{keywords? `No users matched the search query "${keywords}"`@@ -93,8 +96,13 @@ const UsersList = ({<UserListItemkey={x.id}user={x}- canRemoveUser={canRemoveUser}- canRemoveMFAFactors={canRemoveMFAFactors}+ permissions={{+ canRemoveUser,+ canRemoveMFAFactors,+ canSendMagicLink,+ canSendRecovery,+ canSendOtp,+ }}setSelectedUser={setSelectedUser}setUserSidePanelOpen={setUserSidePanelOpen}/>diff --git a/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx b/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsxindex 42eae7eadd2..f07de284c09 100644--- a/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx+++ b/apps/studio/components/interfaces/Auth/Users/UsersListItem.tsx@@ -9,16 +9,20 @@ import { getDisplayName } from './UserListItem.utils'interface UserListItemProps {user: User- canRemoveUser: boolean- canRemoveMFAFactors: boolean+ permissions: {+ canRemoveUser: boolean+ canRemoveMFAFactors: boolean+ canSendMagicLink: boolean+ canSendRecovery: boolean+ canSendOtp: boolean+ }setSelectedUser: (user: User) => voidsetUserSidePanelOpen: (open: boolean) => void}const UserListItem = ({user,- canRemoveUser,- canRemoveMFAFactors,+ permissions,setSelectedUser,setUserSidePanelOpen,}: UserListItemProps) => {@@ -65,8 +69,7 @@ const UserListItem = ({<Table.td className="table-cell"><UserDropdownuser={user}- canRemoveUser={canRemoveUser}- canRemoveMFAFactors={canRemoveMFAFactors}+ permissions={permissions}setSelectedUser={setSelectedUser}setUserSidePanelOpen={setUserSidePanelOpen}/>diff --git a/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx b/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsxindex 4389287d2fa..3f9df41f012 100644--- a/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx+++ b/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx@@ -1,19 +1,27 @@-import { useParams } from 'common'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { partition } from 'lodash'-import { MessageCircle } from 'lucide-react'+import { ExternalLink, MessageCircle } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'import toast from 'react-hot-toast'+import { useParams } from 'common'import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import NoPermission from 'components/ui/NoPermission'import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'import { useBranchesDisableMutation } from 'data/branches/branches-disable-mutation'import { Branch, useBranchesQuery } from 'data/branches/branches-query'import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'-import { useSelectedOrganization, useSelectedProject, useUrlState } from 'hooks'-import { Button, IconExternalLink, IconGitHub } from 'ui'+import {+ useCheckPermissions,+ useSelectedOrganization,+ useSelectedProject,+ useUrlState,+} from 'hooks'+import { Button, IconGitHub } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'import { BranchLoader, BranchManagementSection, BranchRow } from './BranchPanels'@@ -47,6 +55,14 @@ const BranchManagement = () => {const [showDisableBranching, setShowDisableBranching] = useState(false)const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()+ const canReadBranches = useCheckPermissions(PermissionAction.READ, 'preview_branches')+ const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {+ resource: { is_default: false },+ })+ const canDisableBranching = useCheckPermissions(PermissionAction.DELETE, 'preview_branches', {+ resource: { is_default: true },+ })+const {data: connections,error: connectionsError,@@ -186,7 +202,7 @@ const BranchManagement = () => {Branching Feedback</a></Button>- <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ <Button type="default" icon={<ExternalLink strokeWidth={1.5} />}><Linktarget="_blank"rel="noreferrer"@@ -195,128 +211,154 @@ const BranchManagement = () => {Documentation</Link></Button>- <Button type="primary" onClick={() => setShowCreateBranch(true)}>+ <ButtonTooltip+ type="primary"+ disabled={!canCreateBranches}+ onClick={() => setShowCreateBranch(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create branches',+ },+ }}+ >Create branch- </Button>+ </ButtonTooltip></div></div>- {isErrorConnections && (- <AlertError- error={connectionsError}- subject="Failed to retrieve GitHub integration connection"- />- )}+ {!canReadBranches ? (+ <NoPermission resourceText="view this project's branches" />+ ) : (+ <>+ {isErrorConnections && (+ <AlertError+ error={connectionsError}+ subject="Failed to retrieve GitHub integration connection"+ />+ )}- {isSuccessConnections && (- <div className="border rounded-lg px-6 py-2 flex items-center justify-between">- <div className="flex items-center gap-x-4">- <div className="w-8 h-8 bg-scale-300 border rounded-md flex items-center justify-center">- <IconGitHub size={18} strokeWidth={2} />- </div>- <p className="text-sm">- {repo ? 'GitHub branch workflow' : 'No GitHub integration connected'}- </p>- <Button asChild type="default" iconRight={<IconExternalLink />}>- <Link passHref href={`/project/${ref}/settings/integrations`}>- Settings- </Link>- </Button>- {repo && (- <Button- type="text"- size="small"- className="text-light hover:text py-1 px-1.5"- iconRight={<IconExternalLink size={14} strokeWidth={1.5} />}- asChild- >- <Link- passHref- target="_blank"- rel="noreferrer"- href={`https://github.com/${repo}`}+ {isSuccessConnections && (+ <div className="border rounded-lg px-6 py-2 flex items-center justify-between">+ <div className="flex items-center gap-x-4">+ <div className="w-8 h-8 bg-scale-300 border rounded-md flex items-center justify-center">+ <IconGitHub size={18} strokeWidth={2} />+ </div>+ <p className="text-sm">GitHub branch workflow</p>+ <Button asChild type="default" iconRight={<ExternalLink size={14} />}>+ <Link passHref href={`/project/${ref}/settings/integrations`}>+ Settings+ </Link>+ </Button>+ <Button+ type="text"+ size="small"+ className="text-light hover:text py-1 px-1.5"+ iconRight={<ExternalLink size={14} strokeWidth={1.5} />}>- {repo}- </Link>- </Button>- )}- </div>- <Button type="default" onClick={() => setShowDisableBranching(true)}>- Disable branching- </Button>- </div>- )}-- {isErrorBranches && tab === 'overview' && (- <AlertError error={branchesError} subject="Failed to retrieve preview branches" />- )}+ <Link+ passHref+ target="_blank"+ rel="noreferrer"+ href={`https://github.com/${repo}`}+ >+ {repo}+ </Link>+ </Button>+ </div>+ <ButtonTooltip+ type="default"+ disabled={!canDisableBranching}+ onClick={() => setShowDisableBranching(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to disable branching',+ },+ }}+ >+ Disable branching+ </ButtonTooltip>+ </div>+ )}- {!isError && (- <>- {tab === 'overview' && (- <Overview- isLoading={isLoading}- isSuccess={isSuccess}- repo={repo}- mainBranch={mainBranch}- previewBranches={previewBranches}- onViewAllBranches={() => setTab('branches')}- onSelectCreateBranch={() => setShowCreateBranch(true)}- onSelectDeleteBranch={setSelectedBranchToDelete}- generateCreatePullRequestURL={generateCreatePullRequestURL}+ {isErrorBranches && tab === 'overview' && (+ <AlertError+ error={branchesError}+ subject="Failed to retrieve preview branches"/>)}- {tab === 'prs' && (- <BranchManagementSection- header={`${branchesWithPRs.length} branches with pull requests found`}- >- {branchesWithPRs.length > 0 ? (- branchesWithPRs.map((branch) => {- return (- <BranchRow- key={branch.id}- repo={repo}- branch={branch}- generateCreatePullRequestURL={generateCreatePullRequestURL}- onSelectDeleteBranch={() => setSelectedBranchToDelete(branch)}- />- )- })- ) : (- <PullRequestsEmptyState- url={generateCreatePullRequestURL()}- hasBranches={previewBranches.length > 0}- />- )}- </BranchManagementSection>- )}- {tab === 'branches' && (- <BranchManagementSection header={`${previewBranches.length} branches found`}>- {isLoadingBranches && <BranchLoader />}- {isErrorBranches && (- <AlertError- error={branchesError}- subject="Failed to retrieve preview branches"- />- )}- {isSuccessBranches && previewBranches.length === 0 && (- <PreviewBranchesEmptyState++ {!isError && (+ <>+ {tab === 'overview' && (+ <Overview+ isLoading={isLoading}+ isSuccess={isSuccess}+ repo={repo}+ mainBranch={mainBranch}+ previewBranches={previewBranches}+ onViewAllBranches={() => setTab('branches')}onSelectCreateBranch={() => setShowCreateBranch(true)}+ onSelectDeleteBranch={setSelectedBranchToDelete}+ generateCreatePullRequestURL={generateCreatePullRequestURL}/>)}- {isSuccessBranches &&- previewBranches.map((branch) => {- return (- <BranchRow- key={branch.id}- repo={repo}- branch={branch}- generateCreatePullRequestURL={generateCreatePullRequestURL}- onSelectDeleteBranch={() => setSelectedBranchToDelete(branch)}+ {tab === 'prs' && (+ <BranchManagementSection+ header={`${branchesWithPRs.length} branches with pull requests found`}+ >+ {branchesWithPRs.length > 0 ? (+ branchesWithPRs.map((branch) => {+ return (+ <BranchRow+ key={branch.id}+ repo={repo}+ branch={branch}+ generateCreatePullRequestURL={generateCreatePullRequestURL}+ onSelectDeleteBranch={() => setSelectedBranchToDelete(branch)}+ />+ )+ })+ ) : (+ <PullRequestsEmptyState+ url={generateCreatePullRequestURL()}+ hasBranches={previewBranches.length > 0}/>- )- })}- </BranchManagementSection>+ )}+ </BranchManagementSection>+ )}+ {tab === 'branches' && (+ <BranchManagementSection+ header={`${previewBranches.length} branches found`}+ >+ {isLoadingBranches && <BranchLoader />}+ {isErrorBranches && (+ <AlertError+ error={branchesError}+ subject="Failed to retrieve preview branches"+ />+ )}+ {isSuccessBranches && previewBranches.length === 0 && (+ <PreviewBranchesEmptyState+ onSelectCreateBranch={() => setShowCreateBranch(true)}+ />+ )}+ {isSuccessBranches &&+ previewBranches.map((branch) => {+ return (+ <BranchRow+ key={branch.id}+ repo={repo}+ branch={branch}+ generateCreatePullRequestURL={generateCreatePullRequestURL}+ onSelectDeleteBranch={() => setSelectedBranchToDelete(branch)}+ />+ )+ })}+ </BranchManagementSection>+ )}+ </>)}</>)}diff --git a/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx b/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsxindex a9a003d6e22..9c652c916ae 100644--- a/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx+++ b/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx@@ -1,7 +1,18 @@import * as Tooltip from '@radix-ui/react-tooltip'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import dayjs from 'dayjs'-import { Clock, GitPullRequest, Infinity, RefreshCw, Trash2 } from 'lucide-react'+import {+ ArrowRight,+ Clock,+ ExternalLink,+ GitPullRequest,+ Infinity,+ MoreVertical,+ RefreshCw,+ Shield,+ Trash2,+} from 'lucide-react'import Link from 'next/link'import { PropsWithChildren, ReactNode, useState } from 'react'import toast from 'react-hot-toast'@@ -12,6 +23,7 @@ import { useBranchQuery } from 'data/branches/branch-query'import { useBranchResetMutation } from 'data/branches/branch-reset-mutation'import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'import type { Branch } from 'data/branches/branches-query'+import { useCheckPermissions } from 'hooks'import {Badge,Button,@@ -19,10 +31,6 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,- IconArrowRight,- IconExternalLink,- IconMoreVertical,- IconShield,TooltipContent_Shadcn_,TooltipTrigger_Shadcn_,Tooltip_Shadcn_,@@ -96,6 +104,8 @@ export const BranchRow = ({const { ref: projectRef } = useParams()const isActive = projectRef === branch?.project_ref+ const canDeleteBranches = useCheckPermissions(PermissionAction.DELETE, 'preview_branches')+const daysFromNow = dayjs().diff(dayjs(branch.updated_at), 'day')const formattedTimeFromNow = dayjs(branch.updated_at).fromNow()const formattedUpdatedAt = dayjs(branch.updated_at).format('DD MMM YYYY, HH:mm:ss (ZZ)')@@ -124,6 +134,7 @@ export const BranchRow = ({const isBranchActiveHealthy = data?.status === 'ACTIVE_HEALTHY'+ const [showConfirmResetModal, setShowConfirmResetModal] = useState(false)const [showBranchModeSwitch, setShowBranchModeSwitch] = useState(false)const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({@@ -138,9 +149,7 @@ export const BranchRow = ({updateBranch({ id: branch.id, projectRef, persistent: !branch.persistent })}- const [showConfirmResetModal, setShowConfirmResetModal] = useState(false)-- const { mutate, isLoading: isResetting } = useBranchResetMutation({+ const { mutate: resetBranch, isLoading: isResetting } = useBranchResetMutation({onSuccess() {toast.success('Success! Please allow a few seconds for the branch to reset.')setShowConfirmResetModal(false)@@ -148,11 +157,8 @@ export const BranchRow = ({})function onConfirmReset() {- if (!projectRef) {- throw new Error('Invalid project reference')- }-- mutate({ id: branch.id, projectRef })+ if (!projectRef) throw new Error('Invalid project reference')+ resetBranch({ id: branch.id, projectRef })}return (@@ -166,7 +172,7 @@ export const BranchRow = ({className="max-w-[300px]"icon={isMain ? (- <IconShield strokeWidth={2} className="text-amber-900" />+ <Shield strokeWidth={2} className="text-amber-900" />) : branch.persistent ? (<Infinity size={16} />) : null@@ -212,7 +218,7 @@ export const BranchRow = ({<div className="flex items-center gap-x-2">{repo && (<>- <Button asChild type="default" iconRight={<IconExternalLink />}>+ <Button asChild type="default" iconRight={<ExternalLink size={14} />}><Linktarget="_blank"rel="noreferrer"@@ -224,7 +230,7 @@ export const BranchRow = ({</Button><DropdownMenu modal={false}><DropdownMenuTrigger asChild>- <Button type="text" icon={<IconMoreVertical />} className="px-1" />+ <Button type="text" icon={<MoreVertical />} className="px-1" /></DropdownMenuTrigger><DropdownMenuContent className="p-0 w-56" side="bottom" align="end"><Link passHref href={`/project/${projectRef}/settings/integrations`}>@@ -240,7 +246,7 @@ export const BranchRow = ({) : (<div className="flex items-center gap-x-2">{branch.pr_number === undefined ? (- <Button asChild type="default" iconRight={<IconExternalLink />}>+ <Button asChild type="default" iconRight={<ExternalLink size={14} />}><Link passHref target="_blank" rel="noreferrer" href={createPullRequestURL}>Create Pull Request</Link>@@ -255,11 +261,7 @@ export const BranchRow = ({><GitPullRequest size={14} />#{branch.pr_number}</Link>- <IconArrowRight- className="mx-1 text-foreground-light"- strokeWidth={1.5}- size={16}- />+ <ArrowRight className="mx-1 text-foreground-light" strokeWidth={1.5} size={16} /><Button asChild type="default"><LinkpassHref@@ -274,7 +276,7 @@ export const BranchRow = ({)}{shouldRenderLogsButton && (- <Button asChild type="default" iconRight={<IconExternalLink />}>+ <Button asChild type="default" iconRight={<ExternalLink size={14} />}><Link passHref target="_blank" rel="noreferrer" href={checkRunLogsURL}>View Logs</Link>@@ -283,9 +285,9 @@ export const BranchRow = ({<DropdownMenu modal={false}><DropdownMenuTrigger asChild>- <Button type="text" icon={<IconMoreVertical />} className="px-1" />+ <Button type="text" icon={<MoreVertical />} className="px-1" /></DropdownMenuTrigger>- <DropdownMenuContent className="p-0 w-56" side="bottom" align="end">+ <DropdownMenuContent className="w-56" side="bottom" align="end"><Tooltip_Shadcn_><TooltipTrigger_Shadcn_ asChild={isBranchActiveHealthy} className="w-full"><DropdownMenuItem@@ -299,7 +301,7 @@ export const BranchRow = ({</DropdownMenuItem></TooltipTrigger_Shadcn_>{!isBranchActiveHealthy && (- <TooltipContent_Shadcn_ side="top">+ <TooltipContent_Shadcn_ side="left">Branch is still initializing. Please wait for the branch to become healthybefore resetting</TooltipContent_Shadcn_>@@ -326,21 +328,31 @@ export const BranchRow = ({</DropdownMenuItem></TooltipTrigger_Shadcn_>{!isBranchActiveHealthy && (- <TooltipContent_Shadcn_ side="top">+ <TooltipContent_Shadcn_ side="left">Branch is still initializing. Please wait for the branch to become healthybefore switching modes</TooltipContent_Shadcn_>)}</Tooltip_Shadcn_>- <DropdownMenuItem- className="gap-x-2"- onSelect={() => onSelectDeleteBranch?.()}- onClick={() => onSelectDeleteBranch?.()}- >- <Trash2 size={14} />- Delete branch- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild={canDeleteBranches} className="w-full">+ <DropdownMenuItem+ className="gap-x-2"+ disabled={!canDeleteBranches}+ onSelect={() => onSelectDeleteBranch?.()}+ onClick={() => onSelectDeleteBranch?.()}+ >+ <Trash2 size={14} />+ Delete branch+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canDeleteBranches && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to delete branches+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu>@@ -359,6 +371,7 @@ export const BranchRow = ({Are you sure you want to reset the "{branch.name}" branch? All data will be deleted.</p></ConfirmationModal>+<ConfirmationModalvariant={'default'}visible={showBranchModeSwitch}diff --git a/apps/studio/components/interfaces/BranchManagement/BranchStatusBadge.tsx b/apps/studio/components/interfaces/BranchManagement/BranchStatusBadge.tsxindex b58cc28e327..8e566ab7778 100644--- a/apps/studio/components/interfaces/BranchManagement/BranchStatusBadge.tsx+++ b/apps/studio/components/interfaces/BranchManagement/BranchStatusBadge.tsx@@ -43,9 +43,9 @@ const STATUS_TO_LABEL: Record<Status, string> = {MIGRATIONS_PASSED: 'Migrations applied successfully',FUNCTIONS_DEPLOYED: 'Functions deployed',FUNCTIONS_FAILED: 'Functions failed to deploy',- PAUSE_FAILED: 'Pause failed',- RESTORE_FAILED: 'Restore failed',RESTARTING: 'Restarting',+ RESTORE_FAILED: 'Failed to restore',+ PAUSE_FAILED: 'Failed to pause',}const BranchStatusBadge = ({ status }: BranchStatusBadgeProps) => {diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsxindex c17ece367d3..4485f1befb6 100644--- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx+++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx@@ -30,6 +30,7 @@ import {Input_Shadcn_,Modal,} from 'ui'+import { Check, Loader2 } from 'lucide-react'interface CreateBranchModalProps {visible: boolean@@ -145,7 +146,7 @@ const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps) => {header="Create a new preview branch"confirmText="Create Preview Branch">- <Modal.Content className="">+ <Modal.Content>{isLoadingConnections && <GenericSkeletonLoader />}{isErrorConnections && (<AlertError@@ -183,7 +184,7 @@ const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps) => {control={form.control}name="branchName"render={({ field }) => (- <FormItem_Shadcn_ className="relative">+ <FormItem_Shadcn_ className="relative flex flex-col gap-y-1"><label className="text-sm text-foreground-light">Choose your branch to create a preview from</label>@@ -192,9 +193,9 @@ const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps) => {</FormControl_Shadcn_><div className="absolute top-9 right-3">{isChecking ? (- <IconLoader className="animate-spin" />+ <Loader2 size={14} className="animate-spin" />) : isValid ? (- <IconCheck className="text-brand" strokeWidth={2} />+ <Check size={14} className="text-brand" strokeWidth={2} />) : null}</div>diff --git a/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx b/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsxindex fd958345fe8..1f4f99f03da 100644--- a/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx+++ b/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx@@ -1,14 +1,20 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { ExternalLink, GitPullRequest } from 'lucide-react'import Link from 'next/link'import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'-import { useFlag } from 'hooks'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useCheckPermissions, useFlag } from 'hooks'import { useAppStateSnapshot } from 'state/app-state'-import { Button, IconExternalLink, IconGitBranch, IconGitPullRequest } from 'ui'+import { Button, IconGitBranch } from 'ui'export const BranchingEmptyState = () => {const snap = useAppStateSnapshot()const hasAccessToBranching = useFlag<boolean>('branchManagement')+ const canEnableBranching = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {+ resource: { is_default: true },+ })return (<ProductEmptyState title="Database Branching">@@ -17,28 +23,32 @@ export const BranchingEmptyState = () => {? 'Create preview branches to experiment changes to your database schema in a safe, non-destructible environment.': 'Database Branching is currently in early access and not available publicly yet.'}</p>- {hasAccessToBranching ? (- <div className="!mt-4">- <Button+ <div className="flex items-center space-x-2 !mt-4">+ {hasAccessToBranching && (+ <ButtonTooltip+ disabled={!canEnableBranching}icon={<IconGitBranch strokeWidth={1.5} />}onClick={() => snap.setShowEnableBranchingModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to enable branching',+ },+ }}>Enable branching- </Button>- </div>- ) : (- <div className="flex items-center space-x-2 !mt-4">- <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />} asChild>- <a- target="_blank"- rel="noreferrer"- href="https://supabase.com/docs/guides/platform/branching"- >- View the docs- </a>- </Button>- </div>- )}+ </ButtonTooltip>+ )}+ <Button type="default" icon={<ExternalLink strokeWidth={1.5} />} asChild>+ <a+ target="_blank"+ rel="noreferrer"+ href="https://supabase.com/docs/guides/platform/branching"+ >+ View the docs+ </a>+ </Button>+ </div></ProductEmptyState>)}@@ -60,10 +70,10 @@ export const PullRequestsEmptyState = ({<div className="w-96 border rounded-md mt-4"><div className="px-5 py-3 bg-surface-100 flex items-center justify-between"><div className="flex items-center space-x-4">- <IconGitPullRequest strokeWidth={2} className="text-foreground-light" />+ <GitPullRequest size={18} strokeWidth={2} className="text-foreground-light" /><p>Create a pull request</p></div>- <Button asChild type="default" iconRight={<IconExternalLink />}>+ <Button asChild type="default" iconRight={<ExternalLink size={14} />}><Link passHref target="_blank" rel="noreferrer" href={url}>Github</Link>@@ -74,7 +84,7 @@ export const PullRequestsEmptyState = ({<p>Not sure what to do?</p><p className="text-foreground-light">Browse our documentation</p></div>- <Button type="default" iconRight={<IconExternalLink />}>+ <Button type="default" iconRight={<ExternalLink size={14} />}><Linktarget="_blank"rel="noreferrer"@@ -117,7 +127,7 @@ export const PreviewBranchesEmptyState = ({<p>Not sure what to do?</p><p className="text-foreground-light">Browse our documentation</p></div>- <Button type="default" iconRight={<IconExternalLink />}>+ <Button type="default" iconRight={<ExternalLink size={14} />}><Linktarget="_blank"rel="noreferrer"diff --git a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsx b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsxindex 1ceb3d7e4f5..c275ff157ce 100644--- a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseAccessToken.tsx@@ -1,6 +1,11 @@-import { useState } from 'react'+import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useForm } from 'react-hook-form'+import { z } from 'zod'++import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useCheckPermissions } from 'hooks'import {- Button,FormControl_Shadcn_,FormField_Shadcn_,FormItem_Shadcn_,@@ -8,9 +13,6 @@ import {Input_Shadcn_,Modal,} from 'ui'-import { z } from 'zod'-import { useForm } from 'react-hook-form'-import { zodResolver } from '@hookform/resolvers/zod'type CreateWarehouseProps = {onSubmit: (values: { description: string }) => void@@ -33,11 +35,23 @@ const CreateWarehouseAccessToken = ({ onSubmit, loading, open, setOpen }: Create},})+ const canCreateAccessTokens = useCheckPermissions(PermissionAction.ANALYTICS_READ, 'logflare')+return (<>- <Button type="outline" onClick={() => setOpen(true)}>+ <ButtonTooltip+ disabled={!canCreateAccessTokens}+ type="outline"+ onClick={() => setOpen(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create access tokens',+ },+ }}+ >Create access token- </Button>+ </ButtonTooltip><Modalsize="medium"onCancel={() => {diff --git a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsx b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsxindex 420bb461ce6..37ac896f726 100644--- a/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/CreateWarehouseCollection.tsx@@ -1,21 +1,27 @@-import { useParams } from 'common'-import { useCreateCollection } from 'data/analytics'+import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { PlusIcon } from 'lucide-react'import { useRouter } from 'next/router'import { useEffect, useState } from 'react'-import toast from 'react-hot-toast'-import { Button, FormControl_Shadcn_, FormField_Shadcn_, Form_Shadcn_, Input, Modal } from 'ui'import { useForm } from 'react-hook-form'-import { zodResolver } from '@hookform/resolvers/zod'+import toast from 'react-hot-toast'import { z } from 'zod'+import { FormMessage } from '@ui/components/shadcn/ui/form'+import { useParams } from 'common'+import { useCreateCollection } from 'data/analytics'+import { useCheckPermissions } from 'hooks'+import { Button, FormControl_Shadcn_, FormField_Shadcn_, Form_Shadcn_, Input, Modal } from 'ui'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'export const CreateWarehouseCollectionModal = () => {const [isOpen, setIsOpen] = useState(false)const router = useRouter()const { ref } = useParams()+ const canCreateCollection = useCheckPermissions(PermissionAction.ANALYTICS_WRITE, 'logflare')+const { mutate: createCollection, isLoading } = useCreateCollection({onSuccess: (data) => {setIsOpen(false)@@ -53,14 +59,21 @@ export const CreateWarehouseCollectionModal = () => {return (<>- <Button+ <ButtonTooltiptype="default"+ disabled={!canCreateCollection}className="justify-start flex-grow w-full"icon={<PlusIcon size="14" />}onClick={() => setIsOpen(!isOpen)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create collections',+ },+ }}>New collection- </Button>+ </ButtonTooltip><Modalsize="medium"onCancel={() => setIsOpen(!isOpen)}diff --git a/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsx b/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsxindex fa55cc7f396..474fe34d906 100644--- a/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/WarehouseAccessTokens.tsx@@ -1,17 +1,21 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { MoreVertical, TrashIcon } from 'lucide-react'+import { useState } from 'react'+import toast from 'react-hot-toast'+import { useParams } from 'common'import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'import Table from 'components/to-be-cleaned/Table'import CopyButton from 'components/ui/CopyButton'import { FormHeader } from 'components/ui/Forms'+import NoPermission from 'components/ui/NoPermission'import { ProjectPausedAlert } from 'components/ui/ProjectPausedAlert'import {useCreateWarehouseAccessToken,useDeleteWarehouseAccessToken,useWarehouseAccessTokensQuery,} from 'data/analytics'-import { MoreVertical, TrashIcon } from 'lucide-react'-import { useState } from 'react'-import toast from 'react-hot-toast'+import { useCheckPermissions } from 'hooks'import {Button,Dialog,@@ -25,10 +29,13 @@ import {DropdownMenuItem,DropdownMenuTrigger,Input,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,cn,} from 'ui'import { GenericSkeletonLoader } from 'ui-patterns'import CreateWarehouseAccessToken from './CreateWarehouseAccessToken'+import { TooltipContent } from '@radix-ui/react-tooltip'const AccessTokenItem = ({token,@@ -44,6 +51,7 @@ const AccessTokenItem = ({onDeleteClick: (id: number) => void}) => {const formattedInsertedAt = new Date(inserted_at).toLocaleString()+ const canDeleteAccessTokens = useCheckPermissions(PermissionAction.ANALYTICS_WRITE, 'logflare')return (<Table.tr className="group">@@ -66,17 +74,29 @@ const AccessTokenItem = ({<DropdownMenuTrigger className="h-8 w-8 p-2 focus-visible:outline-none"><MoreVertical size="14" /></DropdownMenuTrigger>- <DropdownMenuContent className="max-w-40">- <DropdownMenuItem- className="flex gap-1.5 "- onClick={(e) => {- e.preventDefault()- onDeleteClick(id)- }}- >- <TrashIcon size="14" />- Revoke token- </DropdownMenuItem>+ <DropdownMenuContent className="max-w-40" align="end">+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ disabled={!canDeleteAccessTokens}+ className="flex gap-1.5 !pointer-events-auto"+ onClick={(e) => {+ if (canDeleteAccessTokens) {+ e.preventDefault()+ onDeleteClick(id)+ }+ }}+ >+ <TrashIcon size="14" />+ Revoke token+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canDeleteAccessTokens && (+ <TooltipContent side="left">+ You need additional permissions to delete access tokens+ </TooltipContent>+ )}+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu></Table.td>@@ -90,8 +110,13 @@ const WarehouseAccessTokens = () => {const projectRef = params.ref as stringconst [open, setOpen] = useState(false)- const accessTokensQuery = useWarehouseAccessTokensQuery({ projectRef })+ const canReadAccessTokens = useCheckPermissions(PermissionAction.ANALYTICS_WRITE, 'logflare')+ const accessTokensQuery = useWarehouseAccessTokensQuery(+ { projectRef },+ { enabled: canReadAccessTokens }+ )const hasAccessTokens = accessTokensQuery.isSuccess && accessTokensQuery.data.data.length > 0+const [tokenToDelete, setTokenToDelete] = useState<string | null>(null)const [showDeleteDialog, setShowDeleteDialog] = useState(false)@@ -118,6 +143,7 @@ const WarehouseAccessTokens = () => {return (<section className="1xl:px-28 mx-auto flex flex-col gap-y-10 px-5 py-6 lg:px-16 xl:px-24 2xl:px-32 pb-32"><FormHeader+ className="!mb-0"title="Warehouse access tokens"description="Manage your warehouse access tokens for this project."actions={@@ -134,59 +160,65 @@ const WarehouseAccessTokens = () => {/>}/>- <div className={cn(['bg-surface-100', 'overflow-hidden', 'rounded-md shadow'])}>- {!isProjectActive ? (- <ProjectPausedAlert- projectRef={projectRef}- description="Restore your project to manage your warehouse access tokens"- />- ) : (- <>- {accessTokensQuery.isLoading ? (- <div className="p-4">- <GenericSkeletonLoader />- </div>- ) : (- <div className="overflow-x-auto">- <Table- head={[- <Table.th key="description">Description</Table.th>,- <Table.th key="token">Created at</Table.th>,- <Table.th key="token">Token</Table.th>,- <Table.th key="actions" />,- ]}- body={- hasAccessTokens ? (- accessTokensQuery.data.data.map((accessToken) => (- <AccessTokenItem- key={accessToken.id + '-wh-access-token'}- token={accessToken.token}- id={accessToken.id}- inserted_at={accessToken.inserted_at}- description={accessToken.description || 'No description'}- onDeleteClick={() => {- setShowDeleteDialog(true)- setTokenToDelete(accessToken.token)- }}- />- ))- ) : (- <Table.tr>- <Table.td colSpan={4}>- <p className="text-sm text-foreground">No access tokens created</p>- <p className="text-sm text-foreground-light">- There are no access tokens associated with your project yet- </p>- </Table.td>- </Table.tr>- )- }- />- </div>- )}- </>- )}- </div>++ {!canReadAccessTokens ? (+ <NoPermission resourceText="view warehouse access tokens" />+ ) : (+ <div className={cn(['bg-surface-100', 'overflow-hidden', 'rounded-md shadow'])}>+ {!isProjectActive ? (+ <ProjectPausedAlert+ projectRef={projectRef}+ description="Restore your project to manage your warehouse access tokens"+ />+ ) : (+ <>+ {accessTokensQuery.isLoading ? (+ <div className="p-4">+ <GenericSkeletonLoader />+ </div>+ ) : (+ <div className="overflow-x-auto">+ <Table+ head={[+ <Table.th key="description">Description</Table.th>,+ <Table.th key="token">Created at</Table.th>,+ <Table.th key="token">Token</Table.th>,+ <Table.th key="actions" />,+ ]}+ body={+ hasAccessTokens ? (+ accessTokensQuery.data.data.map((accessToken) => (+ <AccessTokenItem+ key={accessToken.id + '-wh-access-token'}+ token={accessToken.token}+ id={accessToken.id}+ inserted_at={accessToken.inserted_at}+ description={accessToken.description || 'No description'}+ onDeleteClick={() => {+ setShowDeleteDialog(true)+ setTokenToDelete(accessToken.token)+ }}+ />+ ))+ ) : (+ <Table.tr>+ <Table.td colSpan={4}>+ <p className="text-sm text-foreground">No access tokens created</p>+ <p className="text-sm text-foreground-light">+ There are no access tokens associated with your project yet+ </p>+ </Table.td>+ </Table.tr>+ )+ }+ />+ </div>+ )}+ </>+ )}+ </div>+ )}+<Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}><DialogContent><DialogHeader>diff --git a/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsx b/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsxindex 237e0ed11e7..eff6c5f26bf 100644--- a/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsx+++ b/apps/studio/components/interfaces/DataWarehouse/WarehouseMenuItem.tsx@@ -1,11 +1,17 @@-import { EllipsisHorizontalIcon } from '@heroicons/react/16/solid'-import { useParams } from 'common'-import { useDeleteCollectionMutation, useUpdateCollection } from 'data/analytics'-import { EditIcon, TrashIcon } from 'lucide-react'+import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { EditIcon, MoreHorizontal, TrashIcon } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'+import { useForm } from 'react-hook-form'import toast from 'react-hot-toast'+import { z } from 'zod'++import { FormMessage } from '@ui/components/shadcn/ui/form'+import { useParams } from 'common'+import { useDeleteCollectionMutation, useUpdateCollection } from 'data/analytics'+import { useCheckPermissions } from 'hooks'import {Button,Checkbox_Shadcn_,@@ -20,12 +26,11 @@ import {Form_Shadcn_,Input_Shadcn_,Modal,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,cn,} from 'ui'-import { z } from 'zod'-import { useForm } from 'react-hook-form'-import { zodResolver } from '@hookform/resolvers/zod'-import { FormMessage } from '@ui/components/shadcn/ui/form'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'type Props = {@@ -44,6 +49,8 @@ export const WarehouseMenuItem = ({ item }: Props) => {const [showUpdateDialog, setShowUpdateDialog] = useState(false)const [showDeleteDialog, setDeleteDialog] = useState(false)+ const canUpdateCollection = useCheckPermissions(PermissionAction.ANALYTICS_WRITE, 'logflare')+const updateCollection = useUpdateCollection({onSuccess: () => {toast.success('Collection updated successfully')@@ -102,33 +109,55 @@ export const WarehouseMenuItem = ({ item }: Props) => {loading={isLoading}type="text"className="px-1 opacity-50 hover:opacity-100 !bg-transparent"- icon={<EllipsisHorizontalIcon />}+ icon={<MoreHorizontal />}/></DropdownMenuTrigger><DropdownMenuContentonClick={(e) => {e.stopPropagation()}}- align="start"- className="w-52 *:space-x-2"+ align="end"+ className="w-44 *:space-x-2">- <DropdownMenuItem- onClick={() => {- setShowUpdateDialog(true)- }}- >- <EditIcon size="14" />- <div>Rename</div>- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ disabled={!canUpdateCollection}+ className="!pointer-events-auto"+ onClick={() => {+ if (canUpdateCollection) setShowUpdateDialog(true)+ }}+ >+ <EditIcon size={14} />+ <div>Rename collection</div>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canUpdateCollection && (+ <TooltipContent_Shadcn_ side="right">+ You need additional permissions to rename collections+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_><DropdownMenuSeparator />- <DropdownMenuItem- onClick={async () => {- setDeleteDialog(true)- }}- >- <TrashIcon size="14" />- <div>Delete</div>- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ disabled={!canUpdateCollection}+ className="!pointer-events-auto"+ onClick={async () => {+ if (canUpdateCollection) setDeleteDialog(true)+ }}+ >+ <TrashIcon size={14} />+ <div>Delete collection</div>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canUpdateCollection && (+ <TooltipContent_Shadcn_ side="right">+ You need additional permissions to delete collections+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu></Link>diff --git a/apps/studio/components/interfaces/Database/Backups/BackupItem.tsx b/apps/studio/components/interfaces/Database/Backups/BackupItem.tsxindex d9c8e3144c6..ba80af27977 100644--- a/apps/studio/components/interfaces/Database/Backups/BackupItem.tsx+++ b/apps/studio/components/interfaces/Database/Backups/BackupItem.tsx@@ -1,10 +1,12 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import dayjs from 'dayjs'-import { Badge, Button, IconDownload } from 'ui'+import { Download } from 'lucide-react'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useBackupDownloadMutation } from 'data/database/backup-download-mutation'import type { DatabaseBackup } from 'data/database/backups-query'import { useCheckPermissions } from 'hooks'+import { Badge } from 'ui'interface BackupItemProps {index: number@@ -37,23 +39,41 @@ const BackupItem = ({ index, isHealthy, backup, projectRef, onSelectBackup }: Baif (backup.status === 'COMPLETED')return (<div className="flex space-x-4">- <Button+ <ButtonTooltiptype="default"disabled={!isHealthy || !canTriggerScheduledBackups}onClick={onSelectBackup}+ tooltip={{+ content: {+ side: 'bottom',+ text: !isHealthy+ ? 'Cannot be restored as project is not active'+ : !canTriggerScheduledBackups+ ? 'You need additional permissions to trigger a restore'+ : undefined,+ },+ }}>Restore- </Button>+ </ButtonTooltip>{!backup.isPhysicalBackup && (- <Button+ <ButtonTooltiptype="default"+ icon={<Download />}+ loading={isDownloading}disabled={!canTriggerScheduledBackups || isDownloading}onClick={() => downloadBackup({ ref: projectRef, backup })}- loading={isDownloading}- icon={<IconDownload />}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canTriggerScheduledBackups+ ? 'You need additional permissions to download backups'+ : undefined,+ },+ }}>Download- </Button>+ </ButtonTooltip>)}</div>)diff --git a/apps/studio/components/interfaces/Database/Backups/BackupsList.tsx b/apps/studio/components/interfaces/Database/Backups/BackupsList.tsxindex 069f050a153..a4348a8e66d 100644--- a/apps/studio/components/interfaces/Database/Backups/BackupsList.tsx+++ b/apps/studio/components/interfaces/Database/Backups/BackupsList.tsx@@ -1,19 +1,18 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQueryClient } from '@tanstack/react-query'import dayjs from 'dayjs'-import { AlertCircle, Clock } from 'lucide-react'+import { Clock } from 'lucide-react'import { useRouter } from 'next/router'import { useState } from 'react'import toast from 'react-hot-toast'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'-import InformationBox from 'components/ui/InformationBox'import Panel from 'components/ui/Panel'import UpgradeToPro from 'components/ui/UpgradeToPro'import { useBackupRestoreMutation } from 'data/database/backup-restore-mutation'import { DatabaseBackup, useBackupsQuery } from 'data/database/backups-query'import { setProjectStatus } from 'data/projects/projects-query'-import { useCheckPermissions, useSelectedOrganization } from 'hooks'+import { useCheckPermissions } from 'hooks'import { PROJECT_STATUS } from 'lib/constants'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import BackupItem from './BackupItem'@@ -23,7 +22,6 @@ import BackupsStorageAlert from './BackupsStorageAlert'const BackupsList = () => {const router = useRouter()const queryClient = useQueryClient()- const organization = useSelectedOrganization()const { project: selectedProject } = useProjectContext()const projectRef = selectedProject?.ref || 'default'@@ -81,12 +79,6 @@ const BackupsList = () => {<BackupsEmpty />) : (<>- {!canTriggerScheduledBackups && (- <InformationBox- icon={<AlertCircle size={16} className="text-foreground-light" strokeWidth={2} />}- title="You need additional permissions to trigger a scheduled backup"- />- )}<BackupsStorageAlert /><Panel>{sortedBackups?.map((x, i: number) => {@@ -106,7 +98,7 @@ const BackupsList = () => {)}</div><ConfirmationModal- size="medium"+ size="small"confirmLabel="Confirm restore"confirmLabelLoading="Restoring"visible={selectedBackup !== undefined}@@ -118,7 +110,7 @@ const BackupsList = () => {restoreFromBackup({ ref: projectRef, backup: selectedBackup })}}>- <p>+ <p className="text-sm">Are you sure you want to restore from{' '}{dayjs(selectedBackup?.inserted_at).format('DD MMM YYYY')}? This will destroy any new datawritten since this backup was made.diff --git a/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx b/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsxindex 9ae3cb055db..d6c1003f2ae 100644--- a/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx+++ b/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx@@ -1,33 +1,34 @@-import * as Tooltip from '@radix-ui/react-tooltip'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQueryClient } from '@tanstack/react-query'-import { useParams } from 'common'import { format } from 'date-fns'import dayjs from 'dayjs'+import { ChevronLeft, ChevronRight, HelpCircle } from 'lucide-react'+import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'import DatePicker from 'react-datepicker'-import {- Alert,- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Button,- IconAlertTriangle,- IconChevronLeft,- IconChevronRight,- IconHelpCircle,- Modal,-} from 'ui'+import { useParams } from 'common'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { FormHeader, FormPanel } from 'components/ui/Forms'import InformationBox from 'components/ui/InformationBox'import { useBackupsQuery } from 'data/database/backups-query'import { usePitrRestoreMutation } from 'data/database/pitr-restore-mutation'import { setProjectStatus } from 'data/projects/projects-query'import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'+import { useCheckPermissions } from 'hooks'import { PROJECT_STATUS } from 'lib/constants'-import Link from 'next/link'+import {+ Alert,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ Modal,+} from 'ui'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'import BackupsEmpty from '../BackupsEmpty'+import BackupsStorageAlert from '../BackupsStorageAlert'import type { Timezone } from './PITR.types'import {constrainDateToRange,@@ -38,7 +39,6 @@ import {import PITRStatus from './PITRStatus'import TimeInput from './TimeInput'import { TimezoneSelection } from './TimezoneSelection'-import BackupsStorageAlert from '../BackupsStorageAlert'const PITRSelection = () => {const router = useRouter()@@ -51,6 +51,11 @@ const PITRSelection = () => {const [showConfirmation, setShowConfirmation] = useState(false)const [selectedTimezone, setSelectedTimezone] = useState<Timezone>(getClientTimezone())+ const canTriggerPhysicalBackups = useCheckPermissions(+ PermissionAction.INFRA_EXECUTE,+ 'queue_job.restore.prepare'+ )+const hasReadReplicas = (databases ?? []).length > 1const {@@ -146,7 +151,7 @@ const PITRSelection = () => {<>{hasReadReplicas && (<Alert_Shadcn_ variant="warning">- <IconAlertTriangle strokeWidth={2} />+ <WarningIcon /><AlertTitle_Shadcn_>Unable to restore from PITR as project has read replicas enabled</AlertTitle_Shadcn_>@@ -181,34 +186,24 @@ const PITRSelection = () => {<Button type="default" onClick={onCancel}>Cancel</Button>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="warning"- disabled={isSelectedOutOfRange || !selectedDate}- onClick={() => setShowConfirmation(true)}- >- Review restore details- </Button>- </Tooltip.Trigger>- {isSelectedOutOfRange && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'bg-alternative rounded py-1 px-2 leading-none shadow',- 'border-background border w-48 text-center',- ].join(' ')}- >- <span className="text-foreground text-xs">- Selected date is out of range where backups are available- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>++ <ButtonTooltip+ type="warning"+ disabled={isSelectedOutOfRange || !selectedDate || !canTriggerPhysicalBackups}+ onClick={() => setShowConfirmation(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: isSelectedOutOfRange+ ? 'Selected date is out of range where backups are available'+ : !canTriggerPhysicalBackups+ ? 'You need additional permissions to trigger a restore'+ : undefined,+ },+ }}+ >+ Review restore details+ </ButtonTooltip></div>}>@@ -240,7 +235,7 @@ const PITRSelection = () => {text-foreground-light hover:text-foreground focus:outline-none`}>- <IconChevronLeft size={16} strokeWidth={2} />+ <ChevronLeft size={16} strokeWidth={2} /></button><span className="text-foreground-light text-sm">{format(date, 'MMMM yyyy')}@@ -254,7 +249,7 @@ const PITRSelection = () => {text-foreground-light hover:text-foreground focus:outline-none`}>- <IconChevronRight size={16} strokeWidth={2} />+ <ChevronRight size={16} strokeWidth={2} /></button></div></div>@@ -273,7 +268,7 @@ const PITRSelection = () => {<InformationBoxdefaultVisibilityhideCollapse- icon={<IconHelpCircle strokeWidth={2} />}+ icon={<HelpCircle size={14} strokeWidth={2} />}title="Select a date which you'd like to restore your database to"/></div>@@ -354,8 +349,8 @@ const PITRSelection = () => {)}</>)}+<Modal- closablesize="medium"visible={showConfirmation}onCancel={() => setShowConfirmation(false)}diff --git a/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx b/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsxindex a41a1437a6f..a5fc37ee514 100644--- a/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx+++ b/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx@@ -2,12 +2,13 @@ import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import dayjs from 'dayjs'-import { Button, IconAlertCircle } from 'ui'+import { Button } from 'ui'import { FormPanel } from 'components/ui/Forms'import { useBackupsQuery } from 'data/database/backups-query'import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'import { useCheckPermissions } from 'hooks'+import { AlertCircle } from 'lucide-react'import type { Timezone } from './PITR.types'import { TimezoneSelection } from './TimezoneSelection'@@ -53,14 +54,13 @@ const PITRStatus = ({footer={<div className="flex items-center justify-between p-6"><div className="flex items-center space-x-4">- <IconAlertCircle className="text-foreground-light" size={18} strokeWidth={1.5} />+ <AlertCircle className="text-foreground-light" size={18} strokeWidth={1.5} /><span className="text-foreground-light text-sm">You'll be able to pick the right date and time when you begin</span></div><Tooltip.Root delayDuration={0}><Tooltip.Trigger asChild>- {/* [Joshen TODO] Double check if this is intentional */}<Buttondisabled={hasReadReplicas || !canTriggerPhysicalBackup}onClick={() => onSetConfiguration()}diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsxindex 948219253b8..8be4da04d2e 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx@@ -1,13 +1,14 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import clsx from 'clsx'import { useParams } from 'common'import dayjs from 'dayjs'+import { ExternalLink, Maximize2, Minimize2, Terminal } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useEffect, useMemo, useState } from 'react'import toast from 'react-hot-toast'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import {FormActions,FormHeader,@@ -16,15 +17,23 @@ import {FormSectionContent,FormSectionLabel,} from 'components/ui/Forms'-import Panel from 'components/ui/Panel'import { useProjectApiQuery } from 'data/config/project-api-query'import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'import { useEdgeFunctionDeleteMutation } from 'data/edge-functions/edge-functions-delete-mutation'import { useEdgeFunctionUpdateMutation } from 'data/edge-functions/edge-functions-update-mutation'import { useCheckPermissions } from 'hooks'-import { ExternalLink, Maximize2, Minimize2, Terminal } from 'lucide-react'-import { Alert, Button, Form, Input, Modal, Toggle } from 'ui'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ Form,+ Input,+ Modal,+ Toggle,+} from 'ui'+import { CriticalIcon } from 'ui-patterns/Icons/StatusIcons'import CommandRender from '../CommandRender'import { generateCLICommands } from './EdgeFunctionDetails.utils'@@ -136,7 +145,7 @@ const EdgeFunctionDetails = () => {><FormSection header={<FormSectionLabel>Function Details</FormSectionLabel>}><FormSectionContent loading={selectedFunction === undefined}>- <Input id="name" name="name" label="Name" />+ <Input id="name" name="name" label="Name" disabled={!canUpdateEdgeFunction} /><Inputdisabledid="slug"@@ -168,6 +177,7 @@ const EdgeFunctionDetails = () => {<Toggleid="verify_jwt"name="verify_jwt"+ disabled={!canUpdateEdgeFunction}label="Enforce JWT Verification"descriptionText="Require a valid JWT in the authorization header when invoking the function"/>@@ -235,48 +245,31 @@ const EdgeFunctionDetails = () => {<div className="!mt-8"><FormHeader title="Delete Edge Function" description="" />- <Panel>- <Panel.Content>- <Alert- withIcon- variant="danger"- title="Once your function is deleted, it can no longer be restored"+ <Alert_Shadcn_ variant="destructive">+ <CriticalIcon />+ <AlertTitle_Shadcn_>+ Once your function is deleted, it can no longer be restored+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ Make sure you have made a backup if you want to restore your edge function+ </AlertDescription_Shadcn_>+ <AlertDescription_Shadcn_ className="mt-3">+ <ButtonTooltip+ type="danger"+ disabled={!canUpdateEdgeFunction}+ loading={selectedFunction?.id === undefined}+ onClick={() => setShowDeleteModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to delete edge functions',+ },+ }}>- <p className="mb-3">- Make sure you have made a backup if you want to restore your edge function- </p>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="danger"- disabled={!canUpdateEdgeFunction}- loading={selectedFunction?.id === undefined}- onClick={() => setShowDeleteModal(true)}- >- Delete edge function- </Button>- </Tooltip.Trigger>- {!canUpdateEdgeFunction && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to delete an edge function- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>- </Alert>- </Panel.Content>- </Panel>+ Delete edge function+ </ButtonTooltip>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_></div></div>@@ -290,9 +283,13 @@ const EdgeFunctionDetails = () => {onConfirm={onConfirmDelete}><Modal.Content>- <Alert withIcon variant="warning" title="This action cannot be undone">- Ensure that you have made a backup if you want to restore your edge function- </Alert>+ <Alert_Shadcn_ variant="warning">+ <CriticalIcon />+ <AlertTitle_Shadcn_>This action cannot be undone</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ Ensure that you have made a backup if you want to restore your edge function+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_></Modal.Content></Modal></>diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsxindex 222d25d9e2f..b32e5802335 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecret.tsx@@ -1,6 +1,10 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Trash } from 'lucide-react'+import Table from 'components/to-be-cleaned/Table'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import type { ProjectSecret } from 'data/secrets/secrets-query'-import { Button, IconTrash } from 'ui'+import { useCheckPermissions } from 'hooks'interface EdgeFunctionSecretProps {secret: ProjectSecret@@ -8,6 +12,7 @@ interface EdgeFunctionSecretProps {}const EdgeFunctionSecret = ({ secret, onSelectDelete }: EdgeFunctionSecretProps) => {+ const canUpdateSecrets = useCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')return (<Table.tr><Table.td>@@ -22,11 +27,18 @@ const EdgeFunctionSecret = ({ secret, onSelectDelete }: EdgeFunctionSecretProps)</Table.td><Table.td><div className="flex items-center justify-end">- <Button+ <ButtonTooltiptype="text"- icon={<IconTrash />}+ icon={<Trash />}className="px-1"+ disabled={!canUpdateSecrets}onClick={() => onSelectDelete()}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to delete edge function secrets',+ },+ }}/></div></Table.td>diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsxindex b407f13cd54..ebcfdabd2f3 100644--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx@@ -1,15 +1,19 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'-import Link from 'next/link'+import { ExternalLink, Search } from 'lucide-react'import { useState } from 'react'import toast from 'react-hot-toast'-import { Button, IconExternalLink, IconSearch, Input, Modal } from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import Table from 'components/to-be-cleaned/Table'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import NoPermission from 'components/ui/NoPermission'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useSecretsDeleteMutation } from 'data/secrets/secrets-delete-mutation'import { ProjectSecret, useSecretsQuery } from 'data/secrets/secrets-query'+import { useCheckPermissions } from 'hooks'+import { Button, Input } from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import AddNewSecretModal from './AddNewSecretModal'import EdgeFunctionSecret from './EdgeFunctionSecret'@@ -19,6 +23,9 @@ const EdgeFunctionSecrets = () => {const [showCreateSecret, setShowCreateSecret] = useState(false)const [selectedSecret, setSelectedSecret] = useState<ProjectSecret>()+ const canReadSecrets = useCheckPermissions(PermissionAction.FUNCTIONS_READ, '*')+ const canUpdateSecrets = useCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')+const { data, error, isLoading, isSuccess, isError } = useSecretsQuery({projectRef: projectRef,})@@ -44,74 +51,92 @@ const EdgeFunctionSecrets = () => {{isSuccess && (<div className="space-y-4">- <div className="flex items-center justify-between">- <Input- size="small"- className="w-80"- placeholder="Search for a secret"- value={searchString}- onChange={(e: any) => setSearchString(e.target.value)}- icon={<IconSearch size="tiny" />}- />- <div className="flex items-center space-x-2">- <Button- asChild- type="default"- icon={<IconExternalLink size={14} strokeWidth={1.5} />}- >- <Link- href="https://supabase.com/docs/guides/functions/secrets"- target="_blank"- rel="noreferrer"- >- Documentation- </Link>- </Button>- <Button onClick={() => setShowCreateSecret(true)}>Add new secret</Button>- </div>- </div>- <Table- head={[- <Table.th key="secret-name">Name</Table.th>,- <Table.th key="secret-value">Digest</Table.th>,- <Table.th key="actions" />,- ]}- body={- secrets.length > 0 ? (- secrets.map((secret) => (- <EdgeFunctionSecret- key={secret.name}- secret={secret}- onSelectDelete={() => setSelectedSecret(secret)}- />- ))- ) : secrets.length === 0 && searchString.length > 0 ? (- <Table.tr>- <Table.td colSpan={3}>- <p className="text-sm text-foreground">No results found</p>- <p className="text-sm text-foreground-light">- Your search for "{searchString}" did not return any results- </p>- </Table.td>- </Table.tr>- ) : (- <Table.tr>- <Table.td colSpan={3}>- <p className="text-sm text-foreground">No secrets created</p>- <p className="text-sm text-foreground-light">- There are no secrets associated with your project yet- </p>- </Table.td>- </Table.tr>- )- }- />+ {!canReadSecrets ? (+ <NoPermission resourceText="view this project's edge function secrets" />+ ) : (+ <>+ <div className="flex items-center justify-between">+ <Input+ size="small"+ className="w-80"+ placeholder="Search for a secret"+ value={searchString}+ onChange={(e: any) => setSearchString(e.target.value)}+ icon={<Search size={14} />}+ />+ <div className="flex items-center space-x-2">+ <Button+ asChild+ type="default"+ icon={<ExternalLink size={14} strokeWidth={1.5} />}+ >+ <a+ target="_blank"+ rel="noreferrer"+ href="https://supabase.com/docs/guides/functions/secrets"+ >+ Documentation+ </a>+ </Button>+ <ButtonTooltip+ disabled={!canUpdateSecrets}+ onClick={() => setShowCreateSecret(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to update edge function secrets',+ },+ }}+ >+ Add new secret+ </ButtonTooltip>+ </div>+ </div>+ <Table+ head={[+ <Table.th key="secret-name">Name</Table.th>,+ <Table.th key="secret-value">Digest</Table.th>,+ <Table.th key="actions" />,+ ]}+ body={+ secrets.length > 0 ? (+ secrets.map((secret) => (+ <EdgeFunctionSecret+ key={secret.name}+ secret={secret}+ onSelectDelete={() => setSelectedSecret(secret)}+ />+ ))+ ) : secrets.length === 0 && searchString.length > 0 ? (+ <Table.tr>+ <Table.td colSpan={3}>+ <p className="text-sm text-foreground">No results found</p>+ <p className="text-sm text-foreground-light">+ Your search for "{searchString}" did not return any results+ </p>+ </Table.td>+ </Table.tr>+ ) : (+ <Table.tr>+ <Table.td colSpan={3}>+ <p className="text-sm text-foreground">No secrets created</p>+ <p className="text-sm text-foreground-light">+ There are no secrets associated with your project yet+ </p>+ </Table.td>+ </Table.tr>+ )+ }+ />+ </>+ )}</div>)}<AddNewSecretModal visible={showCreateSecret} onClose={() => setShowCreateSecret(false)} /><ConfirmationModal+ variant="warning"loading={isDeleting}visible={selectedSecret !== undefined}confirmLabel="Delete secret"diff --git a/apps/studio/components/interfaces/HomePageActions.tsx b/apps/studio/components/interfaces/HomePageActions.tsxindex dae381e1fcc..e2ac71353d2 100644--- a/apps/studio/components/interfaces/HomePageActions.tsx+++ b/apps/studio/components/interfaces/HomePageActions.tsx@@ -10,11 +10,15 @@ import {DropdownMenuTrigger,IconSearch,Input,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'import { useOrganizationsQuery } from 'data/organizations/organizations-query'-import { useIsFeatureEnabled } from 'hooks'+import { useCheckPermissions, useIsFeatureEnabled } from 'hooks'import { EMPTY_ARR } from 'lib/void'+import { PermissionAction } from '@supabase/shared-types/out/constants'interface HomePageActionsProps {organizations: { name: string; slug: string }[]diff --git a/apps/studio/components/interfaces/Integrations/IntegrationConnection.tsx b/apps/studio/components/interfaces/Integrations/IntegrationConnection.tsxindex 155a6c070c7..2c006b347ce 100644--- a/apps/studio/components/interfaces/Integrations/IntegrationConnection.tsx+++ b/apps/studio/components/interfaces/Integrations/IntegrationConnection.tsx@@ -1,7 +1,17 @@+import { ChevronDown, Loader2, RefreshCw, Trash } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { forwardRef, useCallback, useState } from 'react'import toast from 'react-hot-toast'++import {+ IntegrationConnection,+ IntegrationConnectionProps,+} from 'components/interfaces/Integrations/IntegrationPanels'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useIntegrationsVercelConnectionSyncEnvsMutation } from 'data/integrations/integrations-vercel-connection-sync-envs-mutation'+import type { IntegrationProjectConnection } from 'data/integrations/integrations.types'+import { useProjectsQuery } from 'data/projects/projects-query'import {Button,DropdownMenu,@@ -9,21 +19,9 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,- IconChevronDown,- IconLoader,- IconRefreshCw,- IconTrash,} from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'-import {- IntegrationConnection,- IntegrationConnectionProps,-} from 'components/interfaces/Integrations/IntegrationPanels'-import { useIntegrationsVercelConnectionSyncEnvsMutation } from 'data/integrations/integrations-vercel-connection-sync-envs-mutation'-import type { IntegrationProjectConnection } from 'data/integrations/integrations.types'-import { useProjectsQuery } from 'data/projects/projects-query'-interface IntegrationConnectionItemProps extends IntegrationConnectionProps {disabled?: booleanonDeleteConnection: (connection: IntegrationProjectConnection) => void | Promise<void>@@ -78,9 +76,19 @@ const IntegrationConnectionItem = forwardRef<HTMLLIElement, IntegrationConnectioshowNode={false}actions={disabled ? (- <Button asChild disabled iconRight={<IconChevronDown />} type="default">- <span>Manage</span>- </Button>+ <ButtonTooltip+ disabled+ iconRight={<ChevronDown size={14} />}+ type="default"+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to manage this connection',+ },+ }}+ >+ Manage+ </ButtonTooltip>) : (<DropdownMenuopen={dropdownVisible}@@ -88,7 +96,7 @@ const IntegrationConnectionItem = forwardRef<HTMLLIElement, IntegrationConnectiomodal={false}><DropdownMenuTrigger asChild>- <Button iconRight={<IconChevronDown />} type="default">+ <Button iconRight={<ChevronDown size={14} />} type="default"><span>Manage</span></Button></DropdownMenuTrigger>@@ -115,9 +123,9 @@ const IntegrationConnectionItem = forwardRef<HTMLLIElement, IntegrationConnectiodisabled={isSyncEnvLoading}>{isSyncEnvLoading ? (- <IconLoader className="animate-spin" size={14} />+ <Loader2 className="animate-spin" size={14} />) : (- <IconRefreshCw size={14} />+ <RefreshCw size={14} />)}<p>Resync environment variables</p></DropdownMenuItem>@@ -126,7 +134,7 @@ const IntegrationConnectionItem = forwardRef<HTMLLIElement, IntegrationConnectio<DropdownMenuSeparator />)}<DropdownMenuItem className="space-x-2" onSelect={() => setIsOpen(true)}>- <IconTrash size={14} />+ <Trash size={14} /><p>Delete connection</p></DropdownMenuItem></DropdownMenuContent>diff --git a/apps/studio/components/interfaces/Integrations/IntegrationPanels.tsx b/apps/studio/components/interfaces/Integrations/IntegrationPanels.tsxindex e8062bc61a8..519a1cdbffe 100644--- a/apps/studio/components/interfaces/Integrations/IntegrationPanels.tsx+++ b/apps/studio/components/interfaces/Integrations/IntegrationPanels.tsx@@ -3,6 +3,7 @@ import Image from 'next/legacy/image'import React from 'react'import { Markdown } from 'components/interfaces/Markdown'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import type {Integration,IntegrationProjectConnection,@@ -10,8 +11,9 @@ import type {import { useProjectsQuery } from 'data/projects/projects-query'import { BASE_PATH } from 'lib/constants'import { getIntegrationConfigurationUrl } from 'lib/integration-utils'+import { ArrowRight } from 'lucide-react'import Link from 'next/link'-import { Badge, Button, cn, IconArrowRight, IconExternalLink, IconGitHub } from 'ui'+import { Badge, Button, IconArrowRight, IconExternalLink, IconGitHub, cn } from 'ui'const ICON_STROKE_WIDTH = 2const ICON_SIZE = 14@@ -250,7 +252,7 @@ const IntegrationConnectionOption = React.forwardRef<HTMLLIElement, IntegrationC<div className="flex gap-2 items-center"><HandleIcon type={'Supabase'} /><span className="text-sm">{project?.name}</span>- <IconArrowRight size={14} className="text-foreground-lighter" strokeWidth={1.5} />+ <ArrowRight size={14} className="text-foreground-lighter" strokeWidth={1.5} /><HandleIcon type={type} /><span className="text-sm">{connection.metadata.name}</span></div>@@ -272,34 +274,40 @@ const EmptyIntegrationConnection = React.forwardRef<showNode?: booleanorgSlug?: stringonClick: () => void+ disabled?: boolean}->(({ className, showNode = true, onClick, ...props }, ref) => {+>(({ className, showNode = true, onClick, disabled, ...props }, ref) => {return (<divref={ref}{...props}className={cn(- showNode && 'ml-6 pl-8 border-l',- 'pb-2 ',+ showNode && 'ml-6 pl-8 mt-4 border-l',+ 'relative pb-2','last:border-l-transparent',- 'relative',className)}>{showNode && (- <div className="absolute w-8 rounded-bl-full border-b border-l border-muted h-10 -left-px"></div>+ <div className="absolute w-8 rounded-bl-full border-b border-l border-muted h-14 -top-4 -left-px"></div>)}<divclassName={cn('w-full','border border-dashed bg-surface-100 border-overlay',- '','flex h-20 px-10 rounded-lg justify-center items-center')}>- <Button type="default" onClick={() => onClick()}>+ <ButtonTooltip+ type="default"+ disabled={disabled}+ onClick={() => onClick()}+ tooltip={{+ content: { side: 'bottom', text: 'Additional permissions required to add connection' },+ }}+ >Add new project connection- </Button>+ </ButtonTooltip></div></div>)@@ -319,8 +327,7 @@ const IntegrationConnectionHeader = React.forwardRef<HTMLDivElement, Integrationref={ref}className={cn(showNode && 'border-l border-muted ml-6 pl-8',- 'pt-6 pb-3',- 'prose text-sm',+ 'py-4 prose text-sm',className)}>diff --git a/apps/studio/components/interfaces/Integrations/ProjectLinker.tsx b/apps/studio/components/interfaces/Integrations/ProjectLinker.tsxindex 8a2cc393f85..992b83b6512 100644--- a/apps/studio/components/interfaces/Integrations/ProjectLinker.tsx+++ b/apps/studio/components/interfaces/Integrations/ProjectLinker.tsx@@ -1,4 +1,4 @@-import { PlusIcon } from 'lucide-react'+import { ChevronDown, PlusIcon } from 'lucide-react'import { useRouter } from 'next/router'import { ReactNode, useEffect, useRef, useState } from 'react'import { toast } from 'react-hot-toast'@@ -205,7 +205,7 @@ const ProjectLinker = ({blockdisabled={defaultSupabaseProjectRef !== undefined || loadingSupabaseProjects}loading={loadingSupabaseProjects}- className="justify-start"+ className="justify-start h-[34px]"icon={<div className="bg-white shadow border rounded p-1 w-6 h-6 flex justify-center items-center"><img@@ -218,7 +218,7 @@ const ProjectLinker = ({iconRight={defaultSupabaseProjectRef === undefined ? (<span className="grow flex justify-end">- <IconChevronDown className={''} />+ <ChevronDown /></span>) : null}@@ -302,7 +302,7 @@ const ProjectLinker = ({blockdisabled={loadingForeignProjects}loading={loadingForeignProjects}- className="justify-start"+ className="justify-start h-[34px]"icon={<div>{selectedForeignProject@@ -312,7 +312,7 @@ const ProjectLinker = ({}iconRight={<span className="grow flex justify-end">- <IconChevronDown className={''} />+ <ChevronDown /></span>}>diff --git a/apps/studio/components/interfaces/Markdown.tsx b/apps/studio/components/interfaces/Markdown.tsxindex 9552649fc04..e210d4beb75 100644--- a/apps/studio/components/interfaces/Markdown.tsx+++ b/apps/studio/components/interfaces/Markdown.tsx@@ -1,4 +1,5 @@import { ReactMarkdown, ReactMarkdownOptions } from 'react-markdown/lib/react-markdown'+import remarkGfm from 'remark-gfm'import { cn } from 'ui'interface Props extends Omit<ReactMarkdownOptions, 'children' | 'node'> {@@ -10,6 +11,7 @@ interface Props extends Omit<ReactMarkdownOptions, 'children' | 'node'> {const Markdown = ({ className, content = '', extLinks = false, ...props }: Props) => {return (<ReactMarkdown+ remarkPlugins={[remarkGfm]}components={{h3: ({ children }) => <h3 className="mb-1">{children}</h3>,a: ({ href, children }) => (diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsxindex 0fb189e20da..9fe26eda583 100644--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx@@ -1,21 +1,12 @@import * as Tooltip from '@radix-ui/react-tooltip'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import dayjs from 'dayjs'+import { ArrowDown, ArrowUp, RefreshCw, User } from 'lucide-react'import Image from 'next/legacy/image'import Link from 'next/link'import { useEffect, useState } from 'react'-import {- Alert,- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Button,- IconAlertTriangle,- IconArrowDown,- IconArrowUp,- IconRefreshCw,- IconUser,-} from 'ui'+import { Alert, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'import { LogDetailsPanel } from 'components/interfaces/AuditLogs'import { ScaffoldContainerLegacy } from 'components/layouts/Scaffold'@@ -23,6 +14,7 @@ import Table from 'components/to-be-cleaned/Table'import AlertError from 'components/ui/AlertError'import { DatePicker } from 'components/ui/DatePicker'import { FilterPopover } from 'components/ui/FilterPopover'+import NoPermission from 'components/ui/NoPermission'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import {AuditLog,@@ -32,6 +24,8 @@ import { useOrganizationMembersQuery } from 'data/organizations/organization-memimport { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'import { useOrganizationsQuery } from 'data/organizations/organizations-query'import { useProjectsQuery } from 'data/projects/projects-query'+import { useCheckPermissions } from 'hooks'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'// [Joshen considerations]// - Maybe fix the height of the table to the remaining height of the viewport, so that the search input is always visible@@ -53,6 +47,8 @@ const AuditLogs = () => {projects: [], // project_ref[]})+ const canReadAuditLogs = useCheckPermissions(PermissionAction.READ, 'notifications')+const { data: projects } = useProjectsQuery()const { data: organizations } = useOrganizationsQuery()const { data: members } = useOrganizationMembersQuery({ slug })@@ -65,6 +61,7 @@ const AuditLogs = () => {iso_timestamp_end: dateRange.to,},{+ enabled: canReadAuditLogs,retry(_failureCount, error) {if (error.message.endsWith('upgrade to team or enterprise plan to access audit logs.')) {return false@@ -120,6 +117,14 @@ const AuditLogs = () => {const currentOrganization = organizations?.find((o) => o.slug === slug)+ if (!canReadAuditLogs) {+ return (+ <ScaffoldContainerLegacy>+ <NoPermission resourceText="view organization audit logs" />+ </ScaffoldContainerLegacy>+ )+ }+return (<><ScaffoldContainerLegacy>@@ -138,8 +143,8 @@ const AuditLogs = () => {variant="default"title="Organization Audit Logs are not available on Free or Pro plans">- <IconAlertTriangle className="h-4 w-4 mt-3" />- <div className="flex flex-row pt-3 pb-2">+ <WarningIcon />+ <div className="flex flex-row pt-1"><div className="grow"><AlertTitle_Shadcn_>Organization Audit Logs are not available on Free or Pro plans@@ -241,7 +246,7 @@ const AuditLogs = () => {<Buttontype="default"disabled={isLoading || isRefetching}- icon={<IconRefreshCw className={isRefetching ? 'animate-spin' : ''} />}+ icon={<RefreshCw className={isRefetching ? 'animate-spin' : ''} />}onClick={() => refetch()}>{isRefetching ? 'Refreshing' : 'Refresh'}@@ -280,9 +285,9 @@ const AuditLogs = () => {className="px-1"icon={dateSortDesc ? (- <IconArrowDown strokeWidth={1.5} size={14} />+ <ArrowDown strokeWidth={1.5} size={14} />) : (- <IconArrowUp strokeWidth={1.5} size={14} />+ <ArrowUp strokeWidth={1.5} size={14} />)}onClick={() => setDateSortDesc(!dateSortDesc)}@@ -329,7 +334,7 @@ const AuditLogs = () => {</div>) : user?.invited_id || user?.username === user?.primary_email ? (<div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">- <IconUser size={18} strokeWidth={2} />+ <User size={18} strokeWidth={2} /></div>) : (<Imagediff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsxindex 83e744ec2bf..dd2ace3203c 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingAddress/BillingAddress.tsx@@ -20,14 +20,6 @@ import { COUNTRIES } from './BillingAddress.constants'const BillingAddress = () => {const { slug } = useParams()- const { data, error, isLoading, isSuccess, isError } = useOrganizationCustomerProfileQuery({- slug,- })- const { mutate: updateCustomerProfile, isLoading: isUpdating } =- useOrganizationCustomerProfileUpdateMutation()-- const formId = 'billing-address-form'- const { city, country, line1, line2, postal_code, state } = data?.address ?? {}const canReadBillingAddress = useCheckPermissions(PermissionAction.BILLING_READ,@@ -38,6 +30,15 @@ const BillingAddress = () => {'stripe.customer')+ const { data, error, isLoading, isSuccess, isError } = useOrganizationCustomerProfileQuery(+ { slug },+ { enabled: canReadBillingAddress }+ )+ const { mutate: updateCustomerProfile, isLoading: isUpdating } =+ useOrganizationCustomerProfileUpdateMutation()++ const formId = 'billing-address-form'+ const { city, country, line1, line2, postal_code, state } = data?.address ?? {}const initialValues = { city, country, line1, line2, postal_code, state }const validate = (values: any) => {diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsxindex 3cb5e7bd1a1..b8c831ebb33 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingBreakdown/BillingBreakdown.tsx@@ -1,4 +1,6 @@import dayjs from 'dayjs'+import Link from 'next/link'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import {@@ -10,18 +12,23 @@ import AlertError from 'components/ui/AlertError'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import UpcomingInvoice from './UpcomingInvoice'-import { useIsFeatureEnabled } from 'hooks'-import Link from 'next/link'+import { useCheckPermissions, useIsFeatureEnabled } from 'hooks'+import NoPermission from 'components/ui/NoPermission'const BillingBreakdown = () => {const { slug: orgSlug } = useParams()+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )+const {data: subscription,error: subscriptionError,isLoading: isLoadingSubscription,isError: isErrorSubscription,- } = useOrgSubscriptionQuery({ orgSlug })+ } = useOrgSubscriptionQuery({ orgSlug }, { enabled: canReadSubscriptions })const invoiceFeatureEnabled = useIsFeatureEnabled('billing:invoices')@@ -43,34 +50,40 @@ const BillingBreakdown = () => {</div></ScaffoldSectionDetail><ScaffoldSectionContent>- {isLoadingSubscription && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}+ {!canReadSubscriptions ? (+ <NoPermission resourceText="view this organization's billing" />+ ) : (+ <>+ {isLoadingSubscription && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}- {isErrorSubscription && (- <AlertError subject="Failed to retrieve subscription" error={subscriptionError} />- )}+ {isErrorSubscription && (+ <AlertError subject="Failed to retrieve subscription" error={subscriptionError} />+ )}- {invoiceFeatureEnabled && (- <>- <p className="text-sm text-foreground-light">- The table shows your upcoming invoice, excluding credits. This invoice will continue- updating until the end of your billing period on {billingCycleEnd.format('MMMM DD')}.- See{' '}- <Link- className="text-green-900 transition hover:text-green-1000"- href={`/org/${orgSlug}/usage`}- >- usage page- </Link>{' '}- for a more detailed usage breakdown.- </p>+ {invoiceFeatureEnabled && (+ <>+ <p className="text-sm text-foreground-light">+ The table shows your upcoming invoice, excluding credits. This invoice will+ continue updating until the end of your billing period on{' '}+ {billingCycleEnd.format('MMMM DD')}. See{' '}+ <Link+ className="text-green-900 transition hover:text-green-1000"+ href={`/org/${orgSlug}/usage`}+ >+ usage page+ </Link>{' '}+ for a more detailed usage breakdown.+ </p>- <UpcomingInvoice slug={orgSlug} />+ <UpcomingInvoice slug={orgSlug} />+ </>+ )}</>)}</ScaffoldSectionContent>diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsxindex e8aeb3ae1cc..cf0e9e9603a 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx@@ -25,7 +25,10 @@ const BillingEmail = () => {const initialValues = { billing_email: billing_email ?? '' }const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')- const canReadBillingEmail = useCheckPermissions(PermissionAction.READ, 'organizations')+ const canReadBillingEmail = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )const { mutate: updateOrganization, isLoading: isUpdating } = useOrganizationUpdateMutation()const onUpdateOrganizationEmail = async (values: any, { resetForm }: any) => {@@ -51,6 +54,8 @@ const BillingEmail = () => {)}+ if (!canReadBillingEmail) return null+return (<ScaffoldSection><ScaffoldSectionDetail>@@ -99,7 +104,7 @@ const BillingEmail = () => {id="billing_email"size="small"label="Email address"- type={canReadBillingEmail ? 'text' : 'password'}+ type="text"disabled={!canUpdateOrganization}/></FormSectionContent>diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsxindex 1860dda5a0c..11137b0f22a 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/CostControl.tsx@@ -1,7 +1,11 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import dayjs from 'dayjs'+import { Calendar, ExternalLink } from 'lucide-react'+import { useTheme } from 'next-themes'+import Image from 'next/image'import Link from 'next/link'import { useParams } from 'common'-import { useTheme } from 'next-themes'import {ScaffoldSection,ScaffoldSectionContent,@@ -9,24 +13,15 @@ import {} from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'import ShimmeringLoader from 'components/ui/ShimmeringLoader'+import { useOrganizationBillingSubscriptionCancelSchedule } from 'data/subscriptions/org-subscription-cancel-schedule-mutation'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'-import { useFlag } from 'hooks'+import { useCheckPermissions, useFlag } from 'hooks'import { BASE_PATH } from 'lib/constants'import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'-import {- Alert,- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Button,- IconCalendar,- IconExternalLink,-} from 'ui'+import { Alert, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'import ProjectUpdateDisabledTooltip from '../ProjectUpdateDisabledTooltip'import SpendCapSidePanel from './SpendCapSidePanel'-import Image from 'next/image'-import dayjs from 'dayjs'-import { useOrganizationBillingSubscriptionCancelSchedule } from 'data/subscriptions/org-subscription-cancel-schedule-mutation'+import NoPermission from 'components/ui/NoPermission'export interface CostControlProps {}@@ -34,6 +29,11 @@ const CostControl = ({}: CostControlProps) => {const { slug } = useParams()const { resolvedTheme } = useTheme()+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )+const snap = useOrgSettingsPageStateSnapshot()const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')const {@@ -42,7 +42,7 @@ const CostControl = ({}: CostControlProps) => {isLoading,isSuccess,isError,- } = useOrgSubscriptionQuery({ orgSlug: slug })+ } = useOrgSubscriptionQuery({ orgSlug: slug }, { enabled: canReadSubscriptions })const currentPlan = subscription?.planconst isUsageBillingEnabled = subscription?.usage_billing_enabled ?? false@@ -74,7 +74,7 @@ const CostControl = ({}: CostControlProps) => {><div className="flex items-center space-x-2 opacity-50 hover:opacity-100 transition"><p className="text-sm m-0">Spend cap</p>- <IconExternalLink size={16} strokeWidth={1.5} />+ <ExternalLink size={16} strokeWidth={1.5} /></div></Link></div>@@ -82,134 +82,140 @@ const CostControl = ({}: CostControlProps) => {</div></ScaffoldSectionDetail><ScaffoldSectionContent>- {isLoading && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}+ {!canReadSubscriptions ? (+ <NoPermission resourceText="update this organization's cost control" />+ ) : (+ <>+ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}- {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}+ {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}- {isSuccess && (- <div className="space-y-6">- {['team', 'enterprise'].includes(currentPlan?.id || '') ? (- <Alert- withIcon- variant="info"- title={`You will be charged for any additional usage on the ${- currentPlan?.name || ''- } plan`}- >- {currentPlan?.name || ''} plan requires you to have spend cap off at all times.- Your projects will never become unresponsive. Only when your{' '}- <Link- href={`/org/${slug}/usage`}- className="text-green-900 transition hover:text-green-1000"- >- included usage- </Link>{' '}- is exceeded will you be charged for any additional usage.- </Alert>- ) : (- <p className="text-sm text-foreground-light">- You can control whether your organization is charged for additional usage beyond- the{' '}- <Link- href={`/org/${slug}/usage`}- className="text-green-900 transition hover:text-green-1000"- >- included quota- </Link>{' '}- of your subscription plan. If you need to go beyond the included quota, simply- switch off your spend cap to pay for additional usage.- </p>- )}+ {isSuccess && (+ <div className="space-y-6">+ {['team', 'enterprise'].includes(currentPlan?.id || '') ? (+ <Alert+ withIcon+ variant="info"+ title={`You will be charged for any additional usage on the ${+ currentPlan?.name || ''+ } plan`}+ >+ {currentPlan?.name || ''} plan requires you to have spend cap off at all+ times. Your projects will never become unresponsive. Only when your{' '}+ <Link+ href={`/org/${slug}/usage`}+ className="text-green-900 transition hover:text-green-1000"+ >+ included usage+ </Link>{' '}+ is exceeded will you be charged for any additional usage.+ </Alert>+ ) : (+ <p className="text-sm text-foreground-light">+ You can control whether your organization is charged for additional usage+ beyond the{' '}+ <Link+ href={`/org/${slug}/usage`}+ className="text-green-900 transition hover:text-green-1000"+ >+ included quota+ </Link>{' '}+ of your subscription plan. If you need to go beyond the included quota, simply+ switch off your spend cap to pay for additional usage.+ </p>+ )}- {/** Toggled on spend cap, scheduled change for end-of-cycle */}- {subscription?.scheduled_plan_change?.target_plan === 'pro' &&- subscription?.scheduled_plan_change?.usage_billing_enabled === false &&- subscription?.plan.id === 'pro' && (- <Alert_Shadcn_ className="mb-2" title="Scheduled downgrade">- <IconCalendar className="h-4 w-4" />- <AlertTitle_Shadcn_>Scheduled change</AlertTitle_Shadcn_>- <AlertDescription_Shadcn_ className="flex flex-col gap-3">- <div>- Your spend cap will be enabled on{' '}- {dayjs(subscription?.scheduled_plan_change?.at).format('MMMM D, YYYY')}. You- will not be charged for any over-usage moving on. If you would like to keep- the spend cap disabled and scale as you go, you may still cancel the- scheduled change.+ {/** Toggled on spend cap, scheduled change for end-of-cycle */}+ {subscription?.scheduled_plan_change?.target_plan === 'pro' &&+ subscription?.scheduled_plan_change?.usage_billing_enabled === false &&+ subscription?.plan.id === 'pro' && (+ <Alert_Shadcn_ className="mb-2" title="Scheduled downgrade">+ <Calendar className="h-4 w-4" />+ <AlertTitle_Shadcn_>Scheduled change</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="flex flex-col gap-3">+ <div>+ Your spend cap will be enabled on{' '}+ {dayjs(subscription?.scheduled_plan_change?.at).format('MMMM D, YYYY')}.+ You will not be charged for any over-usage moving on. If you would like+ to keep the spend cap disabled and scale as you go, you may still cancel+ the scheduled change.+ </div>+ <div>+ <Button+ type="default"+ loading={cancelSubscriptionScheduleLoading}+ onClick={() => {+ return cancelSubscriptionSchedule({ slug: slug! })+ }}+ >+ Cancel+ </Button>+ </div>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ <div className="flex space-x-6">+ <div>+ <div className="rounded-md bg-surface-200 w-[160px] h-[96px] shadow">+ <Image+ alt="Spend Cap"+ width={160}+ height={96}+ src={+ isUsageBillingEnabled+ ? `${BASE_PATH}/img/spend-cap-off${+ resolvedTheme?.includes('dark') ? '' : '--light'+ }.png?v=3`+ : `${BASE_PATH}/img/spend-cap-on${+ resolvedTheme?.includes('dark') ? '' : '--light'+ }.png?v=3`+ }+ /></div>- <div>+ </div>+ <div>+ <p className="mb-1">+ Spend cap is {isUsageBillingEnabled ? 'disabled' : 'enabled'}+ </p>+ <p className="text-sm text-foreground-light">+ {isUsageBillingEnabled ? (+ <span>You will be charged for any usage above the included quota.</span>+ ) : (+ <span>+ You won't be charged any extra for usage. However, your projects could+ become unresponsive or enter read only mode if you exceed the included+ quota.+ </span>+ )}+ </p>+ {isUsageBillingEnabled && (+ <p className="text-sm text-foreground-light mt-1">+ Your projects will never become unresponsive. Only when your usage reaches+ the quota limit will you be charged for any excess usage.+ </p>+ )}+ <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}><Buttontype="default"- loading={cancelSubscriptionScheduleLoading}- onClick={() => {- return cancelSubscriptionSchedule({ slug: slug! })- }}+ className="mt-4 pointer-events-auto"+ disabled={!canChangeTier}+ onClick={() => snap.setPanelKey('costControl')}>- Cancel+ Change spend cap</Button>- </div>- </AlertDescription_Shadcn_>- </Alert_Shadcn_>- )}-- <div className="flex space-x-6">- <div>- <div className="rounded-md bg-surface-200 w-[160px] h-[96px] shadow">- <Image- alt="Spend Cap"- width={160}- height={96}- src={- isUsageBillingEnabled- ? `${BASE_PATH}/img/spend-cap-off${- resolvedTheme?.includes('dark') ? '' : '--light'- }.png?v=3`- : `${BASE_PATH}/img/spend-cap-on${- resolvedTheme?.includes('dark') ? '' : '--light'- }.png?v=3`- }- />+ </ProjectUpdateDisabledTooltip>+ </div></div></div>- <div>- <p className="mb-1">- Spend cap is {isUsageBillingEnabled ? 'disabled' : 'enabled'}- </p>- <p className="text-sm text-foreground-light">- {isUsageBillingEnabled ? (- <span>You will be charged for any usage above the included quota.</span>- ) : (- <span>- You won't be charged any extra for usage. However, your projects could- become unresponsive or enter read only mode if you exceed the included- quota.- </span>- )}- </p>- {isUsageBillingEnabled && (- <p className="text-sm text-foreground-light mt-1">- Your projects will never become unresponsive. Only when your usage reaches the- quota limit will you be charged for any excess usage.- </p>- )}- <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>- <Button- type="default"- className="mt-4 pointer-events-auto"- disabled={!canChangeTier}- onClick={() => snap.setPanelKey('costControl')}- >- Change spend cap- </Button>- </ProjectUpdateDisabledTooltip>- </div>- </div>- </div>+ )}+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsxindex 8dd878640f3..e7d40081633 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditBalance.tsx@@ -1,3 +1,4 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import {ScaffoldSection,@@ -5,15 +6,20 @@ import {ScaffoldSectionDetail,} from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import NoPermission from 'components/ui/NoPermission'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useOrganizationCustomerProfileQuery } from 'data/organizations/organization-customer-profile-query'+import { useCheckPermissions } from 'hooks'import { Badge } from 'ui'const CreditBalance = () => {const { slug } = useParams()- const { data, error, isLoading, isError, isSuccess } = useOrganizationCustomerProfileQuery({- slug,- })+ const canReadCredits = useCheckPermissions(PermissionAction.BILLING_READ, 'stripe.customer')++ const { data, error, isLoading, isError, isSuccess } = useOrganizationCustomerProfileQuery(+ { slug },+ { enabled: canReadCredits }+ )const customerBalance = (data?.balance ?? 0) / 100const isCredit = customerBalance < 0@@ -38,25 +44,34 @@ const CreditBalance = () => {</div></ScaffoldSectionDetail><ScaffoldSectionContent>- {isLoading && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}+ {!canReadCredits ? (+ <NoPermission resourceText="view this organization's credits" />+ ) : (+ <>+ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}- {isError && (- <AlertError subject="Failed to retrieve organization customer profile" error={error} />- )}+ {isError && (+ <AlertError+ subject="Failed to retrieve organization customer profile"+ error={error}+ />+ )}- {isSuccess && (- <div className="flex items-end space-x-1">- {isDebt && <h4 className="opacity-50">-</h4>}- <h4 className="opacity-50">$</h4>- <h2 className="text-4xl relative top-[2px]">{balance}</h2>- {isCredit && <h4 className="opacity-50">/credits</h4>}- </div>+ {isSuccess && (+ <div className="flex items-end space-x-1">+ {isDebt && <h4 className="opacity-50">-</h4>}+ <h4 className="opacity-50">$</h4>+ <h2 className="text-4xl relative top-[2px]">{balance}</h2>+ {isCredit && <h4 className="opacity-50">/credits</h4>}+ </div>+ )}+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/MembersExceedLimitModal.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/MembersExceedLimitModal.tsxindex ca756e99cfd..fbd54c2dec2 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/MembersExceedLimitModal.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/MembersExceedLimitModal.tsx@@ -2,8 +2,6 @@ import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limport { useSelectedOrganization } from 'hooks'import { Button, Modal } from 'ui'-// [Joshen TODO] Check if we still need this?-export interface MembersExceedLimitModalProps {visible: booleanonClose: () => voiddiff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsxindex 0f0a1e4962d..56be387923e 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx@@ -1,13 +1,15 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { isArray } from 'lodash'+import { ChevronRight, ExternalLink } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useEffect, useRef, useState } from 'react'import toast from 'react-hot-toast'+import { billingPartnerLabel } from 'components/interfaces/Billing/Subscription/Subscription.utils'import Table from 'components/to-be-cleaned/Table'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import InformationBox from 'components/ui/InformationBox'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'@@ -23,23 +25,13 @@ import { formatCurrency } from 'lib/helpers'import Telemetry from 'lib/telemetry'import { pickFeatures, pickFooter, plans as subscriptionsPlans } from 'shared-data/plans'import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'-import {- Button,- IconCheck,- IconChevronRight,- IconExternalLink,- IconInfo,- Modal,- SidePanel,- cn,-} from 'ui'+import { Button, IconCheck, IconInfo, Modal, SidePanel, cn } from 'ui'import DowngradeModal from './DowngradeModal'import EnterpriseCard from './EnterpriseCard'import ExitSurveyModal from './ExitSurveyModal'-import UpgradeSurveyModal from './UpgradeModal'import MembersExceedLimitModal from './MembersExceedLimitModal'import PaymentMethodSelection from './PaymentMethodSelection'-import { billingPartnerLabel } from 'components/interfaces/Billing/Subscription/Subscription.utils'+import UpgradeSurveyModal from './UpgradeModal'const PlanUpdateSidePanel = () => {const router = useRouter()@@ -181,7 +173,7 @@ const PlanUpdateSidePanel = () => {header={<div className="flex items-center justify-between"><h4>Change subscription plan for {selectedOrganization?.name}</h4>- <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}><Link href="https://supabase.com/pricing" target="_blank" rel="noreferrer">Pricing</Link>@@ -248,56 +240,41 @@ const PlanUpdateSidePanel = () => {Current plan</Button>) : (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <div>- <Button- block- disabled={- // No self-serve downgrades from Enterprise- subscription?.plan?.id === 'enterprise' || !canUpdateSubscription- }- type={isDowngradeOption ? 'default' : 'primary'}- onClick={() => {- setSelectedTier(plan.id as any)- Telemetry.sendActivity(- {- activity: 'Popup Viewed',- source: 'Dashboard',- data: {- title: isDowngradeOption- ? 'Downgrade'- : 'Upgrade' + ' to ' + plan.name,- section: 'Subscription plan',- },- ...(slug && { orgSlug: slug }),- },- router- )- }}- >- {isDowngradeOption ? 'Downgrade' : 'Upgrade'} to {plan.name}- </Button>- </div>- </Tooltip.Trigger>- {!canUpdateSubscription ? (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You do not have permission to change the subscription plan.- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : null}- </Tooltip.Root>+ <ButtonTooltip+ block+ type={isDowngradeOption ? 'default' : 'primary'}+ disabled={subscription?.plan?.id === 'enterprise' || !canUpdateSubscription}+ onClick={() => {+ setSelectedTier(plan.id as any)+ Telemetry.sendActivity(+ {+ activity: 'Popup Viewed',+ source: 'Dashboard',+ data: {+ title: isDowngradeOption+ ? 'Downgrade'+ : 'Upgrade' + ' to ' + plan.name,+ section: 'Subscription plan',+ },+ ...(slug && { orgSlug: slug }),+ },+ router+ )+ }}+ tooltip={{+ content: {+ side: 'bottom',+ text:+ subscription?.plan?.id === 'enterprise'+ ? 'Reach out to us via support to update your plan from Enterprise'+ : !canUpdateSubscription+ ? 'You do not have permission to change the subscription plan'+ : undefined,+ },+ }}+ >+ {isDowngradeOption ? 'Downgrade' : 'Upgrade'} to {plan.name}+ </ButtonTooltip>)}<div className="border-t my-4" />@@ -400,7 +377,7 @@ const PlanUpdateSidePanel = () => {type="text"className="!pl-0 !pr-1"icon={- <IconChevronRight+ <ChevronRightclassName={cn('transition',usageFeesExpanded.includes(item.description) && 'rotate-90'@@ -495,7 +472,7 @@ const PlanUpdateSidePanel = () => {)}<div className="space-x-3 mt-2">- <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}><Linkhref="https://supabase.com/docs/guides/platform/org-based-billing"target="_blank"@@ -505,11 +482,7 @@ const PlanUpdateSidePanel = () => {</Link></Button>{subscription?.plan?.id === 'free' && (- <Button- asChild- type="default"- icon={<IconExternalLink strokeWidth={1.5} />}- >+ <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}><Linkhref="https://supabase.com/docs/guides/platform/project-transfer"target="_blank"diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsxindex db3a0f34162..14e91063f8a 100644--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/Subscription.tsx@@ -1,5 +1,7 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import dayjs from 'dayjs'+import { Calendar, ExternalLink } from 'lucide-react'import Link from 'next/link'import {@@ -8,21 +10,14 @@ import {ScaffoldSectionDetail,} from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import NoPermission from 'components/ui/NoPermission'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import SparkBar from 'components/ui/SparkBar'import { useOrganizationBillingSubscriptionCancelSchedule } from 'data/subscriptions/org-subscription-cancel-schedule-mutation'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'-import { useFlag } from 'hooks'-import { ExternalLink } from 'lucide-react'+import { useCheckPermissions, useFlag } from 'hooks'import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'-import {- Alert,- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Button,- IconCalendar,-} from 'ui'+import { Alert, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'import ProjectUpdateDisabledTooltip from '../ProjectUpdateDisabledTooltip'import { Restriction } from '../Restriction'import PlanUpdateSidePanel from './PlanUpdateSidePanel'@@ -32,13 +27,18 @@ const Subscription = () => {const snap = useOrgSettingsPageStateSnapshot()const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )+const {data: subscription,error,isLoading,isError,isSuccess,- } = useOrgSubscriptionQuery({ orgSlug: slug })+ } = useOrgSubscriptionQuery({ orgSlug: slug }, { enabled: canReadSubscriptions })const { mutate: cancelSubscriptionSchedule, isLoading: cancelSubscriptionScheduleLoading } =useOrganizationBillingSubscriptionCancelSchedule()@@ -75,154 +75,166 @@ const Subscription = () => {</div></ScaffoldSectionDetail><ScaffoldSectionContent>- {isLoading && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}+ {!canReadSubscriptions ? (+ <NoPermission resourceText="view this organization's subscription" />+ ) : (+ <>+ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}- {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}+ {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}- {isSuccess && (- <div className="space-y-6">- <div>- <p className="text-sm">This organization is currently on the plan:</p>- <p className="text-2xl text-brand uppercase">{currentPlan?.name ?? 'Unknown'}</p>- </div>+ {isSuccess && (+ <div className="space-y-6">+ <div>+ <p className="text-sm">This organization is currently on the plan:</p>+ <p className="text-2xl text-brand uppercase">+ {currentPlan?.name ?? 'Unknown'}+ </p>+ </div>- {subscription?.scheduled_plan_change &&- subscription?.scheduled_plan_change?.target_plan !== subscription.plan.id && (- <Alert_Shadcn_ className="mb-2" title="Scheduled downgrade">- <IconCalendar className="h-4 w-4" />- <AlertTitle_Shadcn_>Scheduled downgrade</AlertTitle_Shadcn_>- <AlertDescription_Shadcn_ className="flex flex-col gap-3">- <div>- Your organization will automatically be downgraded from the{' '}- <span>{subscription.plan.name}</span> plan to the{' '}- <span className="capitalize">- {subscription?.scheduled_plan_change?.target_plan}- </span>{' '}- plan on{' '}- {dayjs(subscription?.scheduled_plan_change?.at).format('MMMM D, YYYY')}. If- you would like to stay on the <span>{subscription.plan.name}</span> plan,- cancel the scheduled downgrade.- </div>- <div>- <Button- type="default"- loading={cancelSubscriptionScheduleLoading}- onClick={() => {- return cancelSubscriptionSchedule({ slug: slug! })- }}+ {subscription?.scheduled_plan_change &&+ subscription?.scheduled_plan_change?.target_plan !== subscription.plan.id && (+ <Alert_Shadcn_ className="mb-2" title="Scheduled downgrade">+ <Calendar className="h-4 w-4" />+ <AlertTitle_Shadcn_>Scheduled downgrade</AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="flex flex-col gap-3">+ <div>+ Your organization will automatically be downgraded from the{' '}+ <span>{subscription.plan.name}</span> plan to the{' '}+ <span className="capitalize">+ {subscription?.scheduled_plan_change?.target_plan}+ </span>{' '}+ plan on{' '}+ {dayjs(subscription?.scheduled_plan_change?.at).format('MMMM D, YYYY')}.+ If you would like to stay on the <span>{subscription.plan.name}</span>{' '}+ plan, cancel the scheduled downgrade.+ </div>+ <div>+ <Button+ type="default"+ loading={cancelSubscriptionScheduleLoading}+ onClick={() => {+ return cancelSubscriptionSchedule({ slug: slug! })+ }}+ >+ Cancel downgrade+ </Button>+ </div>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ <div>+ <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>+ <Button+ type="default"+ className="pointer-events-auto"+ disabled={!canChangeTier}+ onClick={() => snap.setPanelKey('subscriptionPlan')}+ >+ Change subscription plan+ </Button>+ </ProjectUpdateDisabledTooltip>+ {!canChangeTier &&+ (projectUpdateDisabled ? (+ <Alert+ className="mt-2"+ withIcon+ variant="info"+ title={`Unable to update plan from ${planName}`}>- Cancel downgrade- </Button>- </div>- </AlertDescription_Shadcn_>- </Alert_Shadcn_>- )}+ We have temporarily disabled project and subscription changes - our+ engineers are working on a fix.+ </Alert>+ ) : (+ <Alert+ withIcon+ className="mt-2"+ variant="info"+ title={`Unable to update plan from ${planName}`}+ actions={[+ <div key="contact-support">+ <Button asChild type="default">+ <Link+ href={`/support/new?category=sales&subject=Change%20plan%20away%20from%20${planName}`}+ >+ Contact support+ </Link>+ </Button>+ </div>,+ ]}+ >+ Please contact us if you'd like to change your plan.+ </Alert>+ ))}+ </div>- <div>- <ProjectUpdateDisabledTooltip projectUpdateDisabled={projectUpdateDisabled}>- <Button- type="default"- className="pointer-events-auto"- disabled={!canChangeTier}- onClick={() => snap.setPanelKey('subscriptionPlan')}- >- Change subscription plan- </Button>- </ProjectUpdateDisabledTooltip>- {!canChangeTier &&- (projectUpdateDisabled ? (+ {!subscription?.usage_billing_enabled && (<Alert- className="mt-2"withIconvariant="info"- title={`Unable to update plan from ${planName}`}- >- We have temporarily disabled project and subscription changes - our engineers- are working on a fix.- </Alert>- ) : (- <Alert- withIcon- className="mt-2"- variant="info"- title={`Unable to update plan from ${planName}`}- actions={[- <div key="contact-support">- <Button asChild type="default">- <Link- href={`/support/new?category=sales&subject=Change%20plan%20away%20from%20${planName}`}- >- Contact support- </Link>+ title="This organization is limited by the included usage"+ actions={+ currentPlan?.id === 'free' ? (+ <Button+ type="default"+ onClick={() => snap.setPanelKey('subscriptionPlan')}+ >+ Upgrade Plan</Button>- </div>,- ]}+ ) : (+ <Button type="default" onClick={() => snap.setPanelKey('costControl')}>+ Adjust Spend Cap+ </Button>+ )+ }>- Please contact us if you'd like to change your plan.+ <div className="text-sm text-foreground-light mr-2">+ When this organization exceeds its{' '}+ <Link+ href={`/org/${slug}/usage`}+ className="text-sm text-green-900 transition hover:text-green-1000"+ >+ included usage quotas+ </Link>+ , its projects may become unresponsive.{' '}+ {currentPlan?.id === 'free' ? (+ <p className="pr-4 mt-1">+ If you wish to exceed the included usage, you should upgrade to a paid+ plan.+ </p>+ ) : (+ <p className="pr-4 mt-1">+ You currently have Spend Cap enabled - when you exceed your plan's+ limit, you will experience restrictions. To scale seamlessly and pay for+ over-usage, you can adjust your Cost Control settings.+ </p>+ )}+ </div></Alert>- ))}- </div>+ )}- {!subscription?.usage_billing_enabled && (- <Alert- withIcon- variant="info"- title="This organization is limited by the included usage"- actions={- currentPlan?.id === 'free' ? (- <Button type="default" onClick={() => snap.setPanelKey('subscriptionPlan')}>- Upgrade Plan- </Button>- ) : (- <Button type="default" onClick={() => snap.setPanelKey('costControl')}>- Adjust Spend Cap- </Button>- )- }- >- <div className="text-sm text-foreground-light mr-2">- When this organization exceeds its{' '}- <Link- href={`/org/${slug}/usage`}- className="text-sm text-green-900 transition hover:text-green-1000"- >- included usage quotas- </Link>- , its projects may become unresponsive.{' '}- {currentPlan?.id === 'free' ? (- <p className="pr-4 mt-1">- If you wish to exceed the included usage, you should upgrade to a paid plan.- </p>- ) : (- <p className="pr-4 mt-1">- You currently have Spend Cap enabled - when you exceed your plan's limit,- you will experience restrictions. To scale seamlessly and pay for- over-usage, you can adjust your Cost Control settings.- </p>- )}- </div>- </Alert>+ <SparkBar+ type="horizontal"+ value={daysWithinCycle - daysToCycleEnd}+ max={daysWithinCycle}+ barClass="bg-foreground"+ labelBottom={`Current billing cycle (${billingCycleStart.format(+ 'MMM DD'+ )} - ${billingCycleEnd.format('MMM DD')})`}+ bgClass="bg-surface-300"+ labelBottomClass="!text-foreground-light pb-1"+ labelTop={`${daysToCycleEnd} days remaining`}+ />+ </div>)}-- <SparkBar- type="horizontal"- value={daysWithinCycle - daysToCycleEnd}- max={daysWithinCycle}- barClass="bg-foreground"- labelBottom={`Current billing cycle (${billingCycleStart.format(- 'MMM DD'- )} - ${billingCycleEnd.format('MMM DD')})`}- bgClass="bg-surface-300"- labelBottomClass="!text-foreground-light pb-1"- labelTop={`${daysToCycleEnd} days remaining`}- />- </div>+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx b/apps/studio/components/interfaces/Organization/Documents/SOC2.tsxindex c2417c023b8..68107e7d3ef 100644--- a/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx+++ b/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx@@ -1,30 +1,40 @@-import { useParams } from 'common'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Download } from 'lucide-react'import Link from 'next/link'import { useState } from 'react'import toast from 'react-hot-toast'-import { Button, IconDownload, Modal } from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { useParams } from 'common'import {ScaffoldSection,ScaffoldSectionContent,ScaffoldSectionDetail,} from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import NoPermission from 'components/ui/NoPermission'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { getDocument } from 'data/documents/document-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { useCheckPermissions } from 'hooks'+import { Button } from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'const SOC2 = () => {const { slug } = useParams()+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )+const {data: subscription,error,isLoading,isError,isSuccess,- } = useOrgSubscriptionQuery({ orgSlug: slug })+ } = useOrgSubscriptionQuery({ orgSlug: slug }, { enabled: canReadSubscriptions })const currentPlan = subscription?.plan+const [isOpen, setIsOpen] = useState(false)const fetchSOC2 = async (orgSlug: string) => {@@ -48,28 +58,34 @@ const SOC2 = () => {</div></ScaffoldSectionDetail><ScaffoldSectionContent>- {isLoading && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}+ {!canReadSubscriptions ? (+ <NoPermission resourceText="access our SOC2 Type 2 report" />+ ) : (+ <>+ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}- {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}+ {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}- {isSuccess && (- <div className="flex items-center justify-center h-full">- {currentPlan?.id === 'free' || currentPlan?.id === 'pro' ? (- <Link href={`/org/${slug}/billing?panel=subscriptionPlan`}>- <Button type="default">Upgrade to Teams</Button>- </Link>- ) : (- <Button type="default" iconRight={<IconDownload />} onClick={() => setIsOpen(true)}>- Download SOC2 Type 2 Report- </Button>+ {isSuccess && (+ <div className="flex items-center justify-center h-full">+ {currentPlan?.id === 'free' || currentPlan?.id === 'pro' ? (+ <Link href={`/org/${slug}/billing?panel=subscriptionPlan`}>+ <Button type="default">Upgrade to Teams</Button>+ </Link>+ ) : (+ <Button type="default" icon={<Download />} onClick={() => setIsOpen(true)}>+ Download SOC2 Type 2 Report+ </Button>+ )}+ </div>)}- </div>+ </>)}<ConfirmationModalvisible={isOpen}diff --git a/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx b/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsxindex ca032652b0d..ccb5570062f 100644--- a/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx+++ b/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx@@ -1,7 +1,9 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'+import { Download } from 'lucide-react'import Link from 'next/link'import toast from 'react-hot-toast'-import { Button, IconDownload } from 'ui'+import { Button } from 'ui'import {ScaffoldSection,@@ -9,19 +11,25 @@ import {ScaffoldSectionDetail,} from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import NoPermission from 'components/ui/NoPermission'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { getDocument } from 'data/documents/document-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { useCheckPermissions } from 'hooks'const SecurityQuestionnaire = () => {const { slug } = useParams()+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )const {data: subscription,error,isLoading,isError,isSuccess,- } = useOrgSubscriptionQuery({ orgSlug: slug })+ } = useOrgSubscriptionQuery({ orgSlug: slug }, { enabled: canReadSubscriptions })const currentPlan = subscription?.planconst fetchQuestionnaire = async (orgSlug: string) => {@@ -49,34 +57,40 @@ const SecurityQuestionnaire = () => {</div></ScaffoldSectionDetail><ScaffoldSectionContent>- {isLoading && (- <div className="space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- )}+ {!canReadSubscriptions ? (+ <NoPermission resourceText="access our security questionnaire" />+ ) : (+ <>+ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}- {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}+ {isError && <AlertError subject="Failed to retrieve subscription" error={error} />}- {isSuccess && (- <div className="flex items-center justify-center h-full">- {currentPlan?.id === 'free' || currentPlan?.id === 'pro' ? (- <Link href={`/org/${slug}/billing?panel=subscriptionPlan`}>- <Button type="default">Upgrade to Teams</Button>- </Link>- ) : (- <Button- type="default"- iconRight={<IconDownload />}- onClick={() => {- if (slug) fetchQuestionnaire(slug)- }}- >- Download Questionnaire- </Button>+ {isSuccess && (+ <div className="flex items-center justify-center h-full">+ {currentPlan?.id === 'free' || currentPlan?.id === 'pro' ? (+ <Link href={`/org/${slug}/billing?panel=subscriptionPlan`}>+ <Button type="default">Upgrade to Teams</Button>+ </Link>+ ) : (+ <Button+ type="default"+ icon={<Download />}+ onClick={() => {+ if (slug) fetchQuestionnaire(slug)+ }}+ >+ Download Questionnaire+ </Button>+ )}+ </div>)}- </div>+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx b/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsxindex 0a69118189c..5e27ff15dab 100644--- a/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx+++ b/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx@@ -1,3 +1,4 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useCallback } from 'react'import toast from 'react-hot-toast'@@ -11,20 +12,21 @@ import {ScaffoldSectionContent,ScaffoldSectionDetail,} from 'components/layouts/Scaffold'+import NoPermission from 'components/ui/NoPermission'+import { useGitHubAuthorizationQuery } from 'data/integrations/github-authorization-query'import { useGitHubConnectionDeleteMutation } from 'data/integrations/github-connection-delete-mutation'import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'import type { IntegrationProjectConnection } from 'data/integrations/integrations.types'-import { useFlag, useSelectedOrganization } from 'hooks'+import { useCheckPermissions, useFlag, useSelectedOrganization } from 'hooks'import { BASE_PATH } from 'lib/constants'-import { useSidePanelsStateSnapshot } from 'state/side-panels'-import { IntegrationConnectionItem } from '../../Integrations/IntegrationConnection'-import SidePanelGitHubRepoLinker from './SidePanelGitHubRepoLinker'-import SidePanelVercelProjectLinker from './SidePanelVercelProjectLinker'-import { useGitHubAuthorizationQuery } from 'data/integrations/github-authorization-query'import {GITHUB_INTEGRATION_INSTALLATION_URL,GITHUB_INTEGRATION_REVOKE_AUTHORIZATION_URL,} from 'lib/github'+import { useSidePanelsStateSnapshot } from 'state/side-panels'+import { IntegrationConnectionItem } from '../../Integrations/IntegrationConnection'+import SidePanelGitHubRepoLinker from './SidePanelGitHubRepoLinker'+import SidePanelVercelProjectLinker from './SidePanelVercelProjectLinker'const IntegrationImageHandler = ({ title }: { title: 'vercel' | 'github' }) => {return (@@ -39,8 +41,21 @@ const IntegrationImageHandler = ({ title }: { title: 'vercel' | 'github' }) => {const IntegrationSettings = () => {const org = useSelectedOrganization()const hasAccessToBranching = useFlag<boolean>('branchManagement')- const { data: gitHubAuthorization, isLoading: isLoadingGitHubAuthorization } =- useGitHubAuthorizationQuery()++ const canReadGithubConnection = useCheckPermissions(+ PermissionAction.READ,+ 'integrations.github_connections'+ )+ const canCreateGitHubConnection = useCheckPermissions(+ PermissionAction.CREATE,+ 'integrations.github_connections'+ )+ const canUpdateGitHubConnection = useCheckPermissions(+ PermissionAction.UPDATE,+ 'integrations.github_connections'+ )++ const { data: gitHubAuthorization } = useGitHubAuthorizationQuery()const { data: connections } = useGitHubConnectionsQuery({ organizationId: org?.id })const { mutate: deleteGitHubConnection } = useGitHubConnectionDeleteMutation({@@ -100,61 +115,69 @@ The GitHub app will watch for changes in your repository such as file changes, b<IntegrationImageHandler title="github" /></ScaffoldSectionDetail><ScaffoldSectionContent>- <Markdown content={GitHubContentSectionTop} />-- <ul className="flex flex-col gap-y-2">- {connections?.map((connection) => (- <IntegrationConnectionItem- key={connection.id}- connection={{- id: String(connection.id),- added_by: {- id: String(connection.user?.id),- primary_email: connection.user?.primary_email ?? '',- username: connection.user?.username ?? '',- },- foreign_project_id: String(connection.repository.id),- supabase_project_ref: connection.project.ref,- organization_integration_id: 'unused',- inserted_at: connection.inserted_at,- updated_at: connection.updated_at,- metadata: {- name: connection.repository.name,- } as any,- }}- type="GitHub"- onDeleteConnection={onDeleteGitHubConnection}- />- ))}- </ul>- {hasAccessToBranching ? (- <EmptyIntegrationConnection- onClick={onAddGitHubConnection}- orgSlug={org?.slug}- showNode={false}- >- Add new project connection- </EmptyIntegrationConnection>+ {!canReadGithubConnection ? (+ <NoPermission resourceText="view this organization's GitHub connections" />) : (- <p className="text-sm text-foreground-light">- Access to{' '}- <a- href="https://supabase.com/docs/guides/platform/branching"- target="_blank"- rel="noreferrer"- className="text-foreground"- >- branching- </a>{' '}- is required to add GitHub connections.- </p>- )}- {GitHubContentSectionBottom && (- <Markdown- extLinks- content={GitHubContentSectionBottom}- className="text-foreground-lighter"- />+ <>+ <Markdown content={GitHubContentSectionTop} />++ <ul className="flex flex-col gap-y-2">+ {connections?.map((connection) => (+ <IntegrationConnectionItem+ key={connection.id}+ disabled={!canUpdateGitHubConnection}+ connection={{+ id: String(connection.id),+ added_by: {+ id: String(connection.user?.id),+ primary_email: connection.user?.primary_email ?? '',+ username: connection.user?.username ?? '',+ },+ foreign_project_id: String(connection.repository.id),+ supabase_project_ref: connection.project.ref,+ organization_integration_id: 'unused',+ inserted_at: connection.inserted_at,+ updated_at: connection.updated_at,+ metadata: {+ name: connection.repository.name,+ } as any,+ }}+ type="GitHub"+ onDeleteConnection={onDeleteGitHubConnection}+ />+ ))}+ </ul>+ {hasAccessToBranching ? (+ <EmptyIntegrationConnection+ onClick={onAddGitHubConnection}+ orgSlug={org?.slug}+ showNode={false}+ disabled={!canCreateGitHubConnection}+ >+ Add new project connection+ </EmptyIntegrationConnection>+ ) : (+ <p className="text-sm text-foreground-light">+ Access to{' '}+ <a+ href="https://supabase.com/docs/guides/platform/branching"+ target="_blank"+ rel="noreferrer"+ className="text-foreground"+ >+ branching+ </a>{' '}+ is required to add GitHub connections.+ </p>+ )}+ {GitHubContentSectionBottom && (+ <Markdown+ extLinks+ content={GitHubContentSectionBottom}+ className="text-foreground-lighter"+ />+ )}+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsx b/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsxindex b3350fd2cb6..a42cdc16807 100644--- a/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsx+++ b/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsx@@ -3,6 +3,7 @@ import { useCallback, useMemo } from 'react'import toast from 'react-hot-toast'import { SidePanel } from 'ui'+import { useParams } from 'common'import { ENV_VAR_RAW_KEYS } from 'components/interfaces/Integrations/Integrations-Vercel.constants'import ProjectLinker, { ForeignProject } from 'components/interfaces/Integrations/ProjectLinker'import { Markdown } from 'components/interfaces/Markdown'@@ -23,6 +24,7 @@ const VERCEL_ICON = ()const SidePanelVercelProjectLinker = () => {+ const { ref } = useParams()const selectedOrganization = useSelectedOrganization()const sidePanelStateSnapshot = useSidePanelsStateSnapshot()const organizationIntegrationId = sidePanelStateSnapshot.vercelConnectionsIntegrationId@@ -119,13 +121,13 @@ const SidePanelVercelProjectLinker = () => {return (<SidePanel- header={'Add new Vercel Project Connection'}+ hideFootersize="large"+ header="Add new Vercel project connection"visible={sidePanelStateSnapshot.vercelConnectionsOpen}- hideFooteronCancel={() => sidePanelStateSnapshot.setVercelConnectionsOpen(false)}>- <div className="py-10 flex flex-col gap-6 bg-studio h-full">+ <div className="py-6 flex flex-col gap-6 bg-studio h-full"><SidePanel.Content><Markdowncontent={`@@ -137,6 +139,7 @@ Check the details below before proceeding</SidePanel.Content><SidePanel.Content className="flex flex-col gap-2"><ProjectLinker+ defaultSupabaseProjectRef={ref}organizationIntegrationId={selectedIntegration?.id}foreignProjects={vercelProjects}supabaseProjects={supabaseProjects}diff --git a/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx b/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsxindex a3f7b5de89b..1abce2bc531 100644--- a/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx+++ b/apps/studio/components/interfaces/Organization/InvoicesSettings/InvoicesSettings.tsx@@ -52,7 +52,11 @@ const InvoicesSettings = () => {}if (!canReadInvoices) {- return <NoPermission resourceText="view invoices" />+ return (+ <ScaffoldContainerLegacy>+ <NoPermission resourceText="view invoices" />+ </ScaffoldContainerLegacy>+ )}return (diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/AuthorizeRequesterDetails.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/AuthorizeRequesterDetails.tsxindex 94dd4006415..a6dc8151b04 100644--- a/apps/studio/components/interfaces/Organization/OAuthApps/AuthorizeRequesterDetails.tsx+++ b/apps/studio/components/interfaces/Organization/OAuthApps/AuthorizeRequesterDetails.tsx@@ -55,19 +55,19 @@ const AuthorizeRequesterDetails = ({scopes,}: AuthorizeRequesterDetailsProps) => {return (- <div className="flex space-y-4 flex-col">- <div className="flex flex-row space-x-4">+ <div className="flex gap-y-4 flex-col">+ <div className="flex flex-row gap-x-4 items-center"><div className="flex items-center"><divclassName="w-14 h-14 md:w-16 md:h-16 bg-center bg-no-repeat bg-cover flex items-center justify-center rounded-md border border-control"style={{- backgroundImage: icon !== null ? `url('${icon}')` : 'none',+ backgroundImage: !!icon ? `url('${icon}')` : 'none',}}>- {icon === null && <p className="text-foreground-light text-lg">{name[0]}</p>}+ {!icon && <p className="text-foreground-light text-lg">{name[0]}</p>}</div></div>- <p className="text-sm text-foreground-light">+ <p className="text-foreground">{name} ({domain}) is requesting API access to an organization.</p></div>diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsxindex 76391b71602..718d6589c07 100644--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx@@ -1,8 +1,12 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import dayjs from 'dayjs'+import { useState } from 'react'+import Table from 'components/to-be-cleaned/Table'import type { OAuthApp } from 'data/oauth/oauth-apps-query'-import dayjs from 'dayjs'+import { useCheckPermissions } from 'hooks'import { copyToClipboard } from 'lib/helpers'-import { useState } from 'react'+import { Check, Clipboard, Edit, MoreVertical, Trash } from 'lucide-react'import {Button,DropdownMenu,@@ -10,11 +14,9 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,- IconCheck,- IconClipboard,- IconEdit,- IconMoreVertical,- IconTrash,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'export interface OAuthAppRowProps {@@ -26,6 +28,9 @@ export interface OAuthAppRowProps {const OAuthAppRow = ({ app, onSelectEdit, onSelectDelete }: OAuthAppRowProps) => {const [isCopied, setIsCopied] = useState(false)+ const canUpdateOAuthApps = useCheckPermissions(PermissionAction.UPDATE, 'approved_oauth_apps')+ const canDeleteOAuthApps = useCheckPermissions(PermissionAction.DELETE, 'approved_oauth_apps')+return (<Table.tr><Table.td>@@ -48,9 +53,7 @@ const OAuthAppRow = ({ app, onSelectEdit, onSelectDelete }: OAuthAppRowProps) =></p><Buttontype="default"- icon={- isCopied ? <IconCheck className="text-brand" strokeWidth={3} /> : <IconClipboard />- }+ icon={isCopied ? <Check className="text-brand" strokeWidth={3} /> : <Clipboard />}className="ml-2 px-1"onClick={() => {copyToClipboard(app.client_id)@@ -71,18 +74,50 @@ const OAuthAppRow = ({ app, onSelectEdit, onSelectDelete }: OAuthAppRowProps) =><Table.td align="right"><DropdownMenu><DropdownMenuTrigger asChild>- <Button type="default" icon={<IconMoreVertical />} className="px-1" />+ <Button type="default" icon={<MoreVertical />} className="px-1" /></DropdownMenuTrigger><DropdownMenuContent align="end" side="bottom">- <DropdownMenuItem className="space-x-2" key="edit" onClick={() => onSelectEdit()}>- <IconEdit />- <p>Edit app</p>- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ key="edit"+ disabled={!canUpdateOAuthApps}+ className="space-x-2 !pointer-events-auto"+ onClick={() => {+ if (canUpdateOAuthApps) onSelectEdit()+ }}+ >+ <Edit size={16} />+ <p>Edit app</p>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canUpdateOAuthApps && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to edit apps+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_><DropdownMenuSeparator />- <DropdownMenuItem className="space-x-2" key="delete" onClick={() => onSelectDelete()}>- <IconTrash />- <p>Delete app</p>- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ disabled={!canDeleteOAuthApps}+ className="space-x-2 !pointer-events-auto"+ key="delete"+ onClick={() => {+ if (canDeleteOAuthApps) onSelectDelete()+ }}+ >+ <Trash size={16} />+ <p>Delete app</p>+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canDeleteOAuthApps && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to delete apps+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu></Table.td>diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsxindex 199205ea534..c9c78078fc1 100644--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx@@ -1,13 +1,17 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useState } from 'react'import { useParams } from 'common'import { ScaffoldContainerLegacy } from 'components/layouts/Scaffold'import Table from 'components/to-be-cleaned/Table'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import NoPermission from 'components/ui/NoPermission'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { AuthorizedApp, useAuthorizedAppsQuery } from 'data/oauth/authorized-apps-query'import { OAuthAppCreateResponse } from 'data/oauth/oauth-app-create-mutation'import { OAuthApp, useOAuthAppsQuery } from 'data/oauth/oauth-apps-query'+import { useCheckPermissions } from 'hooks'import { Alert, Button, IconX, Input } from 'ui'import AuthorizedAppRow from './AuthorizedAppRow'import DeleteAppModal from './DeleteAppModal'@@ -28,13 +32,16 @@ const OAuthApps = () => {const [selectedAppToDelete, setSelectedAppToDelete] = useState<OAuthApp>()const [selectedAppToRevoke, setSelectedAppToRevoke] = useState<AuthorizedApp>()+ const canReadOAuthApps = useCheckPermissions(PermissionAction.READ, 'approved_oauth_apps')+ const canCreateOAuthApps = useCheckPermissions(PermissionAction.CREATE, 'approved_oauth_apps')+const {data: publishedApps,error: publishedAppsError,isLoading: isLoadingPublishedApps,isSuccess: isSuccessPublishedApps,isError: isErrorPublishedApps,- } = useOAuthAppsQuery({ slug })+ } = useOAuthAppsQuery({ slug }, { enabled: canReadOAuthApps })const sortedPublishedApps = publishedApps?.sort((a, b) => {return Number(new Date(a.created_at)) - Number(new Date(b.created_at))@@ -51,6 +58,14 @@ const OAuthApps = () => {return Number(new Date(a.authorized_at)) - Number(new Date(b.authorized_at))})+ if (!canReadOAuthApps) {+ return (+ <ScaffoldContainerLegacy>+ <NoPermission resourceText="view invoices" />+ </ScaffoldContainerLegacy>+ )+ }+return (<><ScaffoldContainerLegacy>@@ -62,9 +77,19 @@ const OAuthApps = () => {Build integrations that extend Supabase's functionality</p></div>- <Button type="primary" onClick={() => setShowPublishModal(true)}>+ <ButtonTooltip+ disabled={!canCreateOAuthApps}+ type="primary"+ onClick={() => setShowPublishModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create apps',+ },+ }}+ >Add application- </Button>+ </ButtonTooltip></div>{isLoadingPublishedApps && (diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsxindex 813f7f8a466..dc31cdc15f9 100644--- a/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx+++ b/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx@@ -1,61 +1,108 @@-import * as Tooltip from '@radix-ui/react-tooltip'+import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'-import { isNil } from 'lodash'import { useEffect, useState } from 'react'+import { useForm } from 'react-hook-form'import toast from 'react-hot-toast'-import { object, string } from 'yup'+import * as z from 'zod'import { useParams } from 'common'-import { useOrganizationMemberInviteCreateMutation } from 'data/organizations/organization-member-invite-create-mutation'-import type { OrganizationMember } from 'data/organizations/organization-members-query'-import { doPermissionsCheck, useGetPermissions } from 'hooks'-import type { Role } from 'types'-import { Button, Form, IconMail, Input, Listbox, Modal } from 'ui'--export interface InviteMemberButtonProps {- orgId: number- userId: number- members: OrganizationMember[]- roles: Role[]- rolesAddable: Number[]-}+import { useOrganizationCreateInvitationMutation } from 'data/organization-members/organization-invitation-create-mutation'+import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'+import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'+import { useProjectsQuery } from 'data/projects/projects-query'+import { doPermissionsCheck, useFlag, useGetPermissions, useSelectedOrganization } from 'hooks'+import { useProfile } from 'lib/profile'+import {+ Button,+ Dialog,+ DialogContent,+ DialogHeader,+ DialogSection,+ DialogSectionSeparator,+ DialogTitle,+ DialogTrigger,+ FormControl_Shadcn_,+ FormDescription_Shadcn_,+ FormField_Shadcn_,+ FormItem_Shadcn_,+ FormLabel_Shadcn_,+ FormMessage_Shadcn_,+ Form_Shadcn_,+ Input_Shadcn_,+ SelectContent_Shadcn_,+ SelectGroup_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ Select_Shadcn_,+ Switch,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+} from 'ui'+import { useGetRolesManagementPermissions } from './TeamSettings.utils'-const InviteMemberButton = ({- orgId,- userId,- members = [],- roles = [],- rolesAddable = [],-}: InviteMemberButtonProps) => {+export const InviteMemberButton = () => {const { slug } = useParams()+ const { profile } = useProfile()+ const organization = useSelectedOrganization()+ const { permissions: permissions } = useGetPermissions()+ const projectLevelPermissionsEnabled = useFlag('projectLevelPermissions')+const [isOpen, setIsOpen] = useState(false)- const { permissions: allPermissions } = useGetPermissions()-- const canInviteMembers = roles.some(({ id: role_id }) =>- doPermissionsCheck(- allPermissions,- PermissionAction.CREATE,- 'user_invites',- { resource: { role_id } },- orgId- )++ const { data: projects } = useProjectsQuery()+ const { data: members } = useOrganizationMembersQuery({ slug })+ const { data: allRoles, isSuccess } = useOrganizationRolesV2Query({ slug })+ const orgScopedRoles = (allRoles?.org_scoped_roles ?? []).sort(+ (a, b) => b.base_role_id - a.base_role_id)- const initialValues = { email: '', role: '' }- const schema = object({- email: string().email('Must be a valid email address').required('Email is required'),- role: string().required('Role is required'),+ const userMemberData = members?.find((m) => m.gotrue_id === profile?.gotrue_id)+ const hasOrgRole =+ (userMemberData?.role_ids ?? []).length === 1 &&+ orgScopedRoles.some((r) => r.id === userMemberData?.role_ids[0])++ const { rolesAddable } = useGetRolesManagementPermissions(+ organization?.id,+ orgScopedRoles,+ permissions ?? []+ )++ const canInviteMembers =+ hasOrgRole &&+ orgScopedRoles.some(({ id: role_id }) =>+ doPermissionsCheck(+ permissions,+ PermissionAction.CREATE,+ 'user_invites',+ { resource: { role_id } },+ organization?.id+ )+ )++ const { mutate: inviteMember, isLoading: isInviting } = useOrganizationCreateInvitationMutation()++ const FormSchema = z.object({+ email: z.string().email('Must be a valid email address').min(1, 'Email is required'),+ role: z.string().min(1, 'Role is required'),+ applyToOrg: z.boolean(),+ projectRef: z.string(),})- const { mutate: inviteMember, isLoading: isInviting } =- useOrganizationMemberInviteCreateMutation()+ const form = useForm<z.infer<typeof FormSchema>>({+ mode: 'onBlur',+ reValidateMode: 'onBlur',+ resolver: zodResolver(FormSchema),+ defaultValues: { email: '', role: '', applyToOrg: true, projectRef: '' },+ })- const onInviteMember = async (values: any, { resetForm }: any) => {- if (!slug) {- throw new Error('slug is required')- }+ const { applyToOrg } = form.watch()++ const onInviteMember = async (values: z.infer<typeof FormSchema>) => {+ if (!slug) return console.error('Slug is required')+ if (profile?.id === undefined) return console.error('Profile ID required')- const existingMember = members.find(+ const existingMember = (members ?? []).find((member) => member.primary_email === values.email.toLowerCase())if (existingMember !== undefined) {@@ -66,135 +113,207 @@ const InviteMemberButton = ({}}- const roleId = Number(values.role)-inviteMember({slug,- invitedEmail: values.email.toLowerCase(),- ownerId: userId,- roleId,+ email: values.email.toLowerCase(),+ roleId: Number(values.role),+ ...(!values.applyToOrg && values.projectRef ? { projects: [values.projectRef] } : {}),},{- onSuccess: (data) => {- if (isNil(data)) {- toast.error('Failed to add member')- } else {- toast.success('Successfully added new member')- setIsOpen(!isOpen)- resetForm({ initialValues: { ...initialValues, role: roleId } })- }+ onSuccess: () => {+ toast.success('Successfully sent invitation to new member')+ setIsOpen(!isOpen)++ const developerRole = orgScopedRoles.find((role) => role.name === 'Developer')+ form.reset({+ email: '',+ role: developerRole?.id.toString() ?? '',+ applyToOrg: true,+ projectRef: '',+ })},})}+ useEffect(() => {+ if (isSuccess && isOpen) {+ const developerRole = orgScopedRoles.find((role) => role.name === 'Developer')+ if (developerRole !== undefined) form.setValue('role', developerRole.id.toString())+ }+ }, [isSuccess, isOpen])++ useEffect(() => {+ if (!applyToOrg) {+ const firstProject = projects?.[0]+ if (firstProject !== undefined) form.setValue('projectRef', firstProject.ref)+ } else {+ form.setValue('projectRef', '')+ }+ }, [applyToOrg])+return (- <>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button disabled={!canInviteMembers} onClick={() => setIsOpen(true)}>- Invite- </Button>- </Tooltip.Trigger>- {!canInviteMembers && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to invite a member to this organization- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>- <Modal- hideFooter- size="medium"- layout="vertical"- className="!overflow-visible"- visible={isOpen}- onCancel={() => setIsOpen(false)}- header="Invite a member to this organization"- >- <Form validationSchema={schema} initialValues={initialValues} onSubmit={onInviteMember}>- {({ values, resetForm }: any) => {- // [Alaister] although this "technically" is breaking the rules of React hooks- // it won't error because the hooks are always rendered in the same order- // eslint-disable-next-line react-hooks/rules-of-hooks- useEffect(() => {- // Catches 'roles' when its available and then adds a default value for role select- if (roles) {- resetForm({- values: {- ...initialValues,- role: roles.find((role) => role.name === 'Developer')?.id,- },- initialValues: {- ...initialValues,- role: roles.find((role) => role.name === 'Developer')?.id,- },- })- }- }, [roles])-- const selectedRole = roles.find((role) => role.id === Number(values.role))- const invalidRoleSelected = values.role && !rolesAddable.includes(Number(values.role))-- return (- <>- <Modal.Content className="space-y-4">- {roles && (- <Listbox- id="role"- name="role"- label="Member role"- error={- invalidRoleSelected- ? `You need additional permissions to assign users the role of ${selectedRole?.name}`- : ''- }- >- {roles.map((role: any) => (- <Listbox.Option key={role.id} value={role.id} label={role.name}>- {role.name}- </Listbox.Option>- ))}- </Listbox>+ <Dialog open={isOpen} onOpenChange={setIsOpen}>+ <DialogTrigger asChild>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ disabled={!canInviteMembers}+ className="pointer-events-auto"+ onClick={() => setIsOpen(true)}+ >+ Invite+ </Button>+ </TooltipTrigger_Shadcn_>+ {!canInviteMembers && (+ <TooltipContent_Shadcn_ side="bottom">+ You need additional permissions to invite a member to this organization+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_>+ </DialogTrigger>+ <DialogContent size="medium">+ <DialogHeader>+ <DialogTitle>Invite a member to this organization</DialogTitle>+ </DialogHeader>+ <DialogSectionSeparator />+ <Form_Shadcn_ {...form}>+ <form+ id="organization-invitation"+ className="flex flex-col gap-y-4"+ onSubmit={form.handleSubmit(onInviteMember)}+ >+ <DialogSection className="flex flex-col gap-y-4 pb-2">+ {projectLevelPermissionsEnabled && (+ <FormField_Shadcn_+ name="applyToOrg"+ control={form.control}+ render={({ field }) => (+ <FormItem_Shadcn_ className="flex items-center gap-x-4">+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={(value) => form.setValue('applyToOrg', value)}+ />+ </FormControl_Shadcn_>+ <FormLabel_Shadcn_>+ Apply role to all projects in the organization+ </FormLabel_Shadcn_>+ </FormItem_Shadcn_>+ )}+ />+ )}+ <FormField_Shadcn_+ name="role"+ control={form.control}+ render={({ field }) => (+ <FormItem_Shadcn_ className="flex flex-col gap-y-2">+ <FormLabel_Shadcn_>Member role</FormLabel_Shadcn_>+ <FormControl_Shadcn_>+ <Select_Shadcn_+ value={field.value}+ onValueChange={(value) => form.setValue('role', value)}+ >+ <SelectTrigger_Shadcn_ className="text-sm h-10 capitalize">+ {orgScopedRoles.find((role) => role.id === Number(field.value))?.name ??+ 'Unknown'}+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {orgScopedRoles.map((role) => {+ const canAssignRole = rolesAddable.includes(role.id)++ return (+ <SelectItem_Shadcn_+ key={role.id}+ value={role.id.toString()}+ className="text-sm [&>span:nth-child(2)]:w-full [&>span:nth-child(2)]:flex [&>span:nth-child(2)]:items-center [&>span:nth-child(2)]:justify-between"+ disabled={!canAssignRole}+ >+ <span>{role.name}</span>+ {!canAssignRole && (+ <span>Additional permissions required to assign role</span>+ )}+ </SelectItem_Shadcn_>+ )+ })}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ </FormItem_Shadcn_>+ )}+ />+ {!applyToOrg && (+ <FormField_Shadcn_+ name="projectRef"+ control={form.control}+ render={({ field }) => (+ <FormItem_Shadcn_ className="flex flex-col gap-y-2">+ <FormLabel_Shadcn_>Select a project</FormLabel_Shadcn_>+ <FormControl_Shadcn_>+ <Select_Shadcn_+ value={field.value}+ onValueChange={(value) => form.setValue('projectRef', value)}+ >+ <SelectTrigger_Shadcn_ className="text-sm h-10 capitalize">+ {(projects ?? []).find((project) => project.ref === field.value)+ ?.name ?? 'Unknown'}+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {(projects ?? []).map((project) => {+ return (+ <SelectItem_Shadcn_+ key={project.id}+ value={project.ref}+ className="text-sm"+ >+ {project.name}+ </SelectItem_Shadcn_>+ )+ })}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ <FormDescription_Shadcn_>+ You can assign roles to multiple projects once the invite is accepted+ </FormDescription_Shadcn_>+ </FormItem_Shadcn_>)}- <Input- autoFocus- id="email"- icon={<IconMail />}- placeholder="Enter email address"- label="Email address"- />- </Modal.Content>- <Modal.Separator />- <Modal.Content>- <Button- block- size="medium"- htmlType="submit"- disabled={isInviting || invalidRoleSelected}- loading={isInviting}- >- Invite new member- </Button>- </Modal.Content>- </>- )- }}- </Form>- </Modal>- </>+ />+ )}+ <FormField_Shadcn_+ name="email"+ control={form.control}+ render={({ field }) => (+ <FormItem_Shadcn_ className="flex flex-col gap-y-2">+ <FormLabel_Shadcn_>Email address</FormLabel_Shadcn_>+ <FormControl_Shadcn_>+ <Input_Shadcn_+ autoFocus+ {...field}+ autoComplete="off"+ disabled={isInviting}+ placeholder="Enter email address"+ />+ </FormControl_Shadcn_>+ <FormMessage_Shadcn_ />+ </FormItem_Shadcn_>+ )}+ />+ </DialogSection>+ <DialogSectionSeparator />+ <DialogSection className="pt-0">+ <Button block htmlType="submit" loading={isInviting} disabled={isInviting}>+ Send invitation+ </Button>+ </DialogSection>+ </form>+ </Form_Shadcn_>+ </DialogContent>+ </Dialog>)}-export default InviteMemberButtondiff --git a/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsxindex 92236c4497d..b8b5a4d55e2 100644--- a/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx+++ b/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx@@ -1,16 +1,21 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { MoreVertical, Trash } from 'lucide-react'import { useState } from 'react'import toast from 'react-hot-toast'import { useParams } from 'common'+import { useOrganizationCreateInvitationMutation } from 'data/organization-members/organization-invitation-create-mutation'+import { useOrganizationDeleteInvitationMutation } from 'data/organization-members/organization-invitation-delete-mutation'+import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'import { useOrganizationMemberDeleteMutation } from 'data/organizations/organization-member-delete-mutation'-import { useOrganizationMemberInviteCreateMutation } from 'data/organizations/organization-member-invite-create-mutation'-import { useOrganizationMemberInviteDeleteMutation } from 'data/organizations/organization-member-invite-delete-mutation'-import type { OrganizationMember } from 'data/organizations/organization-members-query'+import {+ useOrganizationMembersQuery,+ type OrganizationMember,+} from 'data/organizations/organization-members-query'import { usePermissionsQuery } from 'data/permissions/permissions-query'+import { useProjectsQuery } from 'data/projects/projects-query'import { useCheckPermissions, useIsFeatureEnabled, useSelectedOrganization } from 'hooks'-import type { Role } from 'types'+import { useProfile } from 'lib/profile'import {Button,DropdownMenu,@@ -18,42 +23,57 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,- IconMoreHorizontal,- IconTrash,- Modal,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { useGetRolesManagementPermissions } from './TeamSettings.utils'+import { UpdateRolesPanel } from './UpdateRolesPanel/UpdateRolesPanel'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'interface MemberActionsProps {member: OrganizationMember- roles: Role[]}-const MemberActions = ({ member, roles }: MemberActionsProps) => {+export const MemberActions = ({ member }: MemberActionsProps) => {const { slug } = useParams()+ const { profile } = useProfile()+ const [showAccessModal, setShowAccessModal] = useState(false)+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)const organizationMembersDeletionEnabled = useIsFeatureEnabled('organization_members:delete')const selectedOrganization = useSelectedOrganization()const { data: permissions } = usePermissionsQuery()+ const { data: allProjects } = useProjectsQuery()+ const { data: members } = useOrganizationMembersQuery({ slug })+ const { data: allRoles } = useOrganizationRolesV2Query({ slug })++ const orgScopedRoles = allRoles?.org_scoped_roles ?? []+ const projectScopedRoles = allRoles?.project_scoped_roles ?? []+ const isPendingInviteAcceptance = !!member.invited_id++ const userMemberData = members?.find((m) => m.gotrue_id === profile?.gotrue_id)+ const hasOrgRole =+ (userMemberData?.role_ids ?? []).length === 1 &&+ orgScopedRoles.some((r) => r.id === userMemberData?.role_ids[0])+const { rolesRemovable } = useGetRolesManagementPermissions(selectedOrganization?.id,- roles,+ orgScopedRoles.concat(projectScopedRoles),permissions ?? [])- const isPendingInviteAcceptance = member.invited_id-const roleId = member.role_ids?.[0] ?? -1- const canRemoveMember = rolesRemovable.includes((member?.role_ids ?? [-1])[0])- const canResendInvite = useCheckPermissions(PermissionAction.CREATE, 'user_invites', {- resource: { role_id: roleId },- })- const canRevokeInvite = useCheckPermissions(PermissionAction.DELETE, 'user_invites', {- resource: { role_id: roleId },- })-- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)+ const canRemoveMember = member.role_ids.every((id) => rolesRemovable.includes(id))+ const canResendInvite =+ useCheckPermissions(PermissionAction.CREATE, 'user_invites', {+ resource: { role_id: roleId },+ }) && hasOrgRole+ const canRevokeInvite =+ useCheckPermissions(PermissionAction.DELETE, 'user_invites', {+ resource: { role_id: roleId },+ }) && hasOrgRoleconst { mutate: deleteOrganizationMember, isLoading: isDeletingMember } =useOrganizationMemberDeleteMutation({@@ -63,8 +83,8 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {},})- const { mutate: createOrganizationMemberInvite, isLoading: isCreatingInvite } =- useOrganizationMemberInviteCreateMutation({+ const { mutate: inviteMember, isLoading: isCreatingInvite } =+ useOrganizationCreateInvitationMutation({onSuccess: () => {toast.success('Resent the invitation.')},@@ -73,44 +93,55 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {},})- const { mutate: asyncDeleteMemberInvite, isLoading: isDeletingInvite } =- useOrganizationMemberInviteDeleteMutation()+ const { mutate: deleteInvitation, isLoading: isDeletingInvite } =+ useOrganizationDeleteInvitationMutation()- const handleMemberDelete = async () => {+ const isLoading = isDeletingMember || isDeletingInvite || isCreatingInvite++ const handleMemberDelete = () => {if (!slug) return console.error('slug is required')if (!member.gotrue_id) return console.error('gotrue_id is required')deleteOrganizationMember({ slug, gotrueId: member.gotrue_id })}- const handleResendInvite = async (member: OrganizationMember) => {+ const handleResendInvite = (member: OrganizationMember) => {const roleId = (member?.role_ids ?? [])[0]const invitedId = member.invited_idif (!slug) return console.error('Slug is required')if (!invitedId) return console.error('Member invited ID is required')- asyncDeleteMemberInvite(- { slug, invitedId, invalidateDetail: false },+ deleteInvitation(+ { slug, id: invitedId, skipInvalidation: true },{onSuccess: () => {- createOrganizationMemberInvite({- slug,- invitedEmail: member.primary_email!,- ownerId: invitedId,- roleId: roleId,- })+ if (!member.primary_email) return toast.error('Email is required')+ const projectScopedRole = projectScopedRoles.find((role) => role.id === roleId)+ if (projectScopedRole !== undefined) {+ const projects = (projectScopedRole?.project_ids ?? [])+ .map((id) => allProjects?.find((p) => p.id === id)?.ref)+ .filter(Boolean) as string[]+ inviteMember({+ slug,+ email: member.primary_email,+ roleId: projectScopedRole.base_role_id,+ projects,+ })+ } else {+ inviteMember({ slug, email: member.primary_email, roleId })+ }},})}- const handleRevokeInvitation = async (member: OrganizationMember) => {+ const handleRevokeInvitation = (member: OrganizationMember) => {const invitedId = member.invited_idif (!slug) return console.error('Slug is required')if (!invitedId) return console.error('Member invited ID is required')- asyncDeleteMemberInvite(- { slug, invitedId },+ deleteInvitation(+ { slug, id: invitedId },{onSuccess: () => {toast.success('Successfully revoked the invitation.')@@ -122,40 +153,52 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {if (!canRemoveMember || (isPendingInviteAcceptance && !canResendInvite && !canRevokeInvite)) {return (<div className="flex items-center justify-end">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button type="text" icon={<IconMoreHorizontal />} />- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to manage this team member- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>+ <ButtonTooltip+ disabled+ type="text"+ className="px-1.5"+ icon={<MoreVertical size={18} />}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to manage this team member',+ },+ }}+ /></div>)}- const isLoading = isDeletingMember || isDeletingInvite || isCreatingInvite-return (<>- <div className="flex items-center justify-end">+ <div className="flex items-center justify-end gap-x-2">+ <ButtonTooltip+ type="default"+ disabled={isPendingInviteAcceptance || !canRemoveMember}+ onClick={() => setShowAccessModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: isPendingInviteAcceptance+ ? 'Role can only be changed after the user has accepted the invite'+ : !canRemoveMember+ ? 'You need additional permissions to manage this team member'+ : undefined,+ },+ }}+ >+ Manage access+ </ButtonTooltip>+<DropdownMenu><DropdownMenuTrigger asChild>- <Button type="text" disabled={isLoading} loading={isLoading}>- <IconMoreHorizontal />- </Button>+ <Button+ type="text"+ className="px-1.5"+ disabled={isLoading}+ loading={isLoading}+ icon={<MoreVertical />}+ /></DropdownMenuTrigger><DropdownMenuContent side="bottom" align="end"><>@@ -165,18 +208,17 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {<DropdownMenuItem onClick={() => handleRevokeInvitation(member)}><div className="flex flex-col"><p>Cancel invitation</p>- <p className="block opacity-50">Revoke this invitation.</p>+ <p className="text-foreground-lighter">Revoke this invitation.</p></div></DropdownMenuItem>)}- {/* canResendInvite && isExpired */}- {true && (+ {canResendInvite && (<><DropdownMenuSeparator /><DropdownMenuItem onClick={() => handleResendInvite(member)}><div className="flex flex-col"><p>Resend invitation</p>- <p className="block opacity-50">Invites expire after 24hrs.</p>+ <p className="text-foreground-lighter">Invites expire after 24hrs.</p></div></DropdownMenuItem></>@@ -185,13 +227,19 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {) : (organizationMembersDeletionEnabled && (<DropdownMenuItem- className="space-x-2"+ className="space-x-2 items-start"+ disabled={!canRemoveMember}onClick={() => {setIsDeleteModalOpen(true)}}>- <IconTrash size={16} />- <p>Remove member</p>+ <Trash size={16} />+ <div className="flex flex-col">+ <p>Remove member</p>+ {!canRemoveMember && (+ <p className="text-foreground-lighter">Additional permissions required</p>+ )}+ </div></DropdownMenuItem>))}@@ -213,8 +261,12 @@ const MemberActions = ({ member, roles }: MemberActionsProps) => {This is permanent! Are you sure you want to remove {member.primary_email}</p></ConfirmationModal>++ <UpdateRolesPanel+ visible={showAccessModal}+ member={member}+ onClose={() => setShowAccessModal(false)}+ /></>)}--export default MemberActionsdiff --git a/apps/studio/components/interfaces/Organization/TeamSettings/MemberRow.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/MemberRow.tsxindex 955538959a7..6f6d3fa1749 100644--- a/apps/studio/components/interfaces/Organization/TeamSettings/MemberRow.tsx+++ b/apps/studio/components/interfaces/Organization/TeamSettings/MemberRow.tsx@@ -1,78 +1,56 @@-import * as Tooltip from '@radix-ui/react-tooltip'+import { Check, Minus, User, X } from 'lucide-react'import Image from 'next/legacy/image'-import { Dispatch, SetStateAction, useState } from 'react'-import toast from 'react-hot-toast'+import { useState } from 'react'import Table from 'components/to-be-cleaned/Table'+import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'import { OrganizationMember } from 'data/organizations/organization-members-query'-import { usePermissionsQuery } from 'data/permissions/permissions-query'-import { useSelectedOrganization } from 'hooks'+import { useProjectsQuery } from 'data/projects/projects-query'+import { useFlag, useSelectedOrganization } from 'hooks'import { useProfile } from 'lib/profile'-import { Role } from 'types'-import { Badge, IconAlertCircle, IconCheck, IconLoader, IconUser, IconX, Listbox } from 'ui'+import { Badge, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_ } from 'ui'+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'import { getUserDisplayName, isInviteExpired } from '../Organization.utils'-import MemberActions from './MemberActions'-import { useGetRolesManagementPermissions } from './TeamSettings.utils'--export interface SelectedMember extends OrganizationMember {- oldRoleId: number- newRoleId: number-}+import { MemberActions } from './MemberActions'interface MemberRowProps {member: OrganizationMember- roles: Role[]- isLoadingRoles?: boolean- showMfaEnabledColumn?: boolean- setUserRoleChangeModalVisible: Dispatch<SetStateAction<boolean>>- setSelectedMember: Dispatch<SetStateAction<SelectedMember | undefined>>}-const MemberRow = ({- member,- roles,- isLoadingRoles = false,- showMfaEnabledColumn = false,- setUserRoleChangeModalVisible,- setSelectedMember,-}: MemberRowProps) => {+export const MemberRow = ({ member }: MemberRowProps) => {const { profile } = useProfile()+ const { data: projects } = useProjectsQuery()const selectedOrganization = useSelectedOrganization()+ const [hasInvalidImg, setHasInvalidImg] = useState(false)+ const projectLevelPermissionsEnabled = useFlag('projectLevelPermissions')- const { data: permissions } = usePermissionsQuery()+ const { data: roles, isLoading: isLoadingRoles } = useOrganizationRolesV2Query({+ slug: selectedOrganization?.slug,+ })- const { rolesAddable, rolesRemovable } = useGetRolesManagementPermissions(- selectedOrganization?.id,- roles,- permissions ?? []- )-- const [memberRoleId] = member.role_ids ?? []- const role = (roles || []).find((role) => role.id === memberRoleId)const memberIsUser = member.primary_email == profile?.primary_emailconst isInvitedUser = Boolean(member.invited_id)- const canRemoveRole = rolesRemovable.includes(memberRoleId)- const disableRoleEdit = !canRemoveRole || memberIsUser || isInvitedUserconst isEmailUser = member.username === member.primary_emailconst isFlyUser = Boolean(member.primary_email?.endsWith('customer.fly.io'))- const validateSelectedRoleToChange = (roleId: any) => {- if (!role || role.id === roleId) return-- const selectedRole = (roles || []).find((role) => role.id === roleId)- const canAddRole = rolesAddable.includes(selectedRole?.id ?? -1)-- if (!canAddRole) {- return toast.error(- `You do not have permission to update this team member to ${selectedRole!.name}`- )- }-- setUserRoleChangeModalVisible(true)- setSelectedMember({ ...member, oldRoleId: role.id, newRoleId: roleId })- }-- const [hasInvalidImg, setHasInvalidImg] = useState(false)+ // [Joshen] From project role POV, mask any roles for other projects+ const isObfuscated =+ member.role_ids.filter((id) => {+ const role = [+ ...(roles?.org_scoped_roles ?? []),+ ...(roles?.project_scoped_roles ?? []),+ ].find((role) => role.id === id)+ const isOrgScope = role?.project_ids === null+ if (isOrgScope) return false++ const appliedProjects = (role?.project_ids ?? [])+ .map((id) => {+ return projects?.find((p) => p.id === id)?.name ?? ''+ })+ .filter((x) => x.length > 0)++ return appliedProjects.length === 0+ }).length > 0return (<Table.tr>@@ -81,7 +59,7 @@ const MemberRow = ({<div>{isInvitedUser || isEmailUser || isFlyUser || hasInvalidImg ? (<div className="w-[40px] h-[40px] bg-surface-100 border border-overlay rounded-full text-foreground-lighter flex items-center justify-center">- <IconUser strokeWidth={1.5} />+ <User size={20} strokeWidth={1.5} /></div>) : (<Image@@ -96,11 +74,13 @@ const MemberRow = ({/>)}</div>- <div>- <p className="text-foreground">{getUserDisplayName(member)}</p>- {isInvitedUser === undefined && (- <p className="text-foreground-light">{member.primary_email}</p>+ <div className="flex item-center gap-x-2">+ {isInvitedUser === undefined ? (+ <p className="text-foreground-light truncate">{member.primary_email}</p>+ ) : (+ <p className="text-foreground truncate">{getUserDisplayName(member)}</p>)}+ {member.primary_email === profile?.primary_email && <Badge color="scale">You</Badge>}</div></div></Table.td>@@ -113,112 +93,81 @@ const MemberRow = ({)}</Table.td>- {showMfaEnabledColumn && (- <Table.td>- <div className="flex items-center justify-center">- {member.mfa_enabled ? (- <IconCheck className="text-brand" strokeWidth={2} />- ) : (- <IconX className="text-foreground-light" strokeWidth={1.5} />- )}- </div>- </Table.td>- )}-<Table.td>+ <div className="flex items-center justify-center">+ {member.mfa_enabled ? (+ <Check className="text-brand" strokeWidth={2} size={20} />+ ) : (+ <X className="text-foreground-light" strokeWidth={1.5} size={20} />+ )}+ </div>+ </Table.td>++ <Table.td className="max-w-64">{isLoadingRoles ? (- <div className="w-[140px]">- <IconLoader className="animate-spin" size={16} strokeWidth={1.5} />- </div>- ) : role !== undefined ? (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-[140px]" asChild>- <div>- <Listbox- className={disableRoleEdit ? 'pointer-events-none' : ''}- disabled={disableRoleEdit}- value={role.id}- onChange={validateSelectedRoleToChange}- >- {roles.map((r: any) => (- <Listbox.Option- key={r.id}- value={r.id}- label={r.name}- disabled={disableRoleEdit}- className="w-36"- >- {r.name}- </Listbox.Option>- ))}- </Listbox>- </div>- </Tooltip.Trigger>- {isInvitedUser ? (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- Role can only be changed after the user has accepted the invite- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : !memberIsUser && !canRemoveRole ? (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to manage this team member- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : (- <></>- )}- </Tooltip.Root>+ <ShimmeringLoader className="w-32" />+ ) : isObfuscated ? (+ <Minus strokeWidth={1.5} size={20} />) : (- <div className="flex items-center space-x-2">- <p className="text-sm text-foreground-light">Invalid role</p>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <IconAlertCircle size={16} strokeWidth={1.5} />- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- This user has an invalid role, please reach out to us via support- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>- </div>+ member.role_ids.map((id) => {+ const orgScopedRole = (roles?.org_scoped_roles ?? []).find((role) => role.id === id)+ const projectScopedRole = (roles?.project_scoped_roles ?? []).find(+ (role) => role.id === id+ )+ const role = orgScopedRole || projectScopedRole+ const roleName = (role?.name ?? '').split('_')[0]+ const projectsApplied =+ role?.project_ids === null+ ? projects?.map((p) => p.name) ?? []+ : (role?.project_ids ?? [])+ .map((id) => {+ return projects?.find((p) => p.id === id)?.name ?? ''+ })+ .filter((x) => x.length > 0)++ if (projectsApplied.length === 0) return null++ return (+ <div key={`role-${id}`} className="flex items-center gap-x-2">+ <p>{roleName}</p>+ {projectLevelPermissionsEnabled && (+ <>+ <span>•</span>+ {projectsApplied.length === 1 ? (+ <span className="text-foreground truncate" title={projectsApplied[0]}>+ {projectsApplied[0]}+ </span>+ ) : (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <span className="text-foreground">+ {role?.project_ids === null+ ? 'Organization'+ : `${projectsApplied.length} project${projectsApplied.length > 1 ? 's' : ''}`}+ </span>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom" className="flex flex-col gap-y-1">+ {projectsApplied+ ?.slice(0, 2)+ .map((name) => <span key={name}>{name}</span>)}+ {projectsApplied.length > 2 && (+ <span>+ And {projectsApplied.length - 2} other project+ {projectsApplied.length > 4 ? 's' : ''}+ </span>+ )}+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ )}+ </>+ )}+ </div>+ )+ }))}</Table.td>- <Table.td>{!memberIsUser && <MemberActions member={member} roles={roles} />}</Table.td>++ <Table.td>{!memberIsUser && <MemberActions member={member} />}</Table.td></Table.tr>)}--export default MemberRowdiff --git a/apps/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/MembersView.tsxindex cdd992ecab9..11946169f56 100644--- a/apps/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx+++ b/apps/studio/components/interfaces/Organization/TeamSettings/MembersView.tsx@@ -1,17 +1,20 @@-import { useState } from 'react'-import toast from 'react-hot-toast'+import { AlertCircle, HelpCircle } from 'lucide-react'import { useParams } from 'common'import Table from 'components/to-be-cleaned/Table'import AlertError from 'components/ui/AlertError'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'-import { useOrganizationMemberUpdateMutation } from 'data/organizations/organization-member-update-mutation'+import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'-import { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'-import { Button, IconAlertCircle, Loading, Modal } from 'ui'-import { getUserDisplayName } from '../Organization.utils'-import MemberRow, { SelectedMember } from './MemberRow'-import RolesHelperModal from './RolesHelperModal/RolesHelperModal'+import { useProfile } from 'lib/profile'+import {+ Button,+ Loading,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+} from 'ui'+import { MemberRow } from './MemberRow'export interface MembersViewProps {searchString: string@@ -19,6 +22,7 @@ export interface MembersViewProps {const MembersView = ({ searchString }: MembersViewProps) => {const { slug } = useParams()+ const { profile } = useProfile()const {data: members,@@ -27,34 +31,11 @@ const MembersView = ({ searchString }: MembersViewProps) => {isError: isErrorMembers,isSuccess: isSuccessMembers,} = useOrganizationMembersQuery({ slug })- const {- data: rolesData,- error: rolesError,- isLoading: isLoadingRoles,- isError: isErrorRoles,- } = useOrganizationRolesQuery({ slug })- const { mutate: updateOrganizationMember, isLoading } = useOrganizationMemberUpdateMutation({- onSuccess() {- setUserRoleChangeModalVisible(false)- toast.success(`Successfully updated role for ${getUserDisplayName(selectedMember)}`)- },- onError(error) {- toast.error(- `Failed to update role for ${getUserDisplayName(selectedMember)}: ${error.message}`- )- },+ const { error: rolesError, isError: isErrorRoles } = useOrganizationRolesV2Query({+ slug,})const allMembers = members ?? []- const roles = rolesData?.roles ?? []-- // [Joshen] Proactively adding this, can be removed once infra API changes are in- const showMfaEnabledColumn = allMembers.some(- (member) => member.gotrue_id !== undefined && member.mfa_enabled !== undefined- )- const [selectedMember, setSelectedMember] = useState<SelectedMember>()- const [userRoleChangeModalVisible, setUserRoleChangeModalVisible] = useState(false)-const filteredMembers = (!searchString? allMembers@@ -70,21 +51,11 @@ const MembersView = ({ searchString }: MembersViewProps) => {})).slice()- .sort((a, b) => a.username.localeCompare(b.username))-- const getRoleNameById = (id: number | undefined) => {- if (!roles) return id- return roles.find((member) => member.id === id)?.name- }-- const handleRoleChange = async () => {- if (!selectedMember) return-- const { gotrue_id, newRoleId } = selectedMember- if (!slug) return console.error('slug is required')- if (!gotrue_id) return console.error('gotrue_id is required')- updateOrganizationMember({ slug, gotrueId: gotrue_id, roleId: newRoleId })- }+ .sort((a, b) => {+ // [Joshen] Have own account show up top+ if (a.primary_email === profile?.primary_email) return -1+ return a.username.localeCompare(b.username)+ })return (<>@@ -104,38 +75,41 @@ const MembersView = ({ searchString }: MembersViewProps) => {<Tablehead={[<Table.th key="header-user">User</Table.th>,- <Table.th key="header-status"></Table.th>,- ...(showMfaEnabledColumn- ? [- <Table.th key="header-mfa" className="text-center">- Enabled MFA- </Table.th>,- ]- : []),- <Table.th key="header-role" className="flex items-center space-x-2">+ <Table.th key="header-status" className="w-24" />,+ <Table.th key="header-mfa" className="text-center w-32">+ Enabled MFA+ </Table.th>,+ <Table.th key="header-role" className="flex items-center space-x-1"><span>Role</span>- <RolesHelperModal />+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button asChild type="text" className="px-1">+ <a+ target="_blank"+ rel="noreferrer"+ href="https://supabase.com/docs/guides/platform/access-control"+ >+ <HelpCircle size={14} className="text-foreground-light" />+ </a>+ </Button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">+ How to configure access control?+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_></Table.th>,- <Table.th key="header-action"></Table.th>,+ <Table.th key="header-action" />,]}body={[...filteredMembers.map((member) => (- <MemberRow- key={member.gotrue_id}- member={member}- roles={roles}- isLoadingRoles={isLoadingRoles}- showMfaEnabledColumn={showMfaEnabledColumn}- setUserRoleChangeModalVisible={setUserRoleChangeModalVisible}- setSelectedMember={setSelectedMember}- />+ <MemberRow key={member.gotrue_id} member={member} />)),...(searchString.length > 0 && filteredMembers.length === 0? [<Table.tr key="no-results" className="bg-panel-secondary-light"><Table.td colSpan={12}><div className="flex items-center space-x-3 opacity-75">- <IconAlertCircle size={16} strokeWidth={2} />+ <AlertCircle size={16} strokeWidth={2} /><p className="text-foreground-light">No users matched the search query "{searchString}"</p>@@ -157,47 +131,6 @@ const MembersView = ({ searchString }: MembersViewProps) => {</Loading></div>)}-- <Modal- hideFooter- size="medium"- visible={userRoleChangeModalVisible}- onCancel={() => setUserRoleChangeModalVisible(false)}- header="Change role of member"- >- <Modal.Content>- <p className="text-sm text-foreground-light">- You are changing the role of{' '}- <span className="text-foreground">{getUserDisplayName(selectedMember)}</span> from{' '}- <span className="text-foreground">{getRoleNameById(selectedMember?.oldRoleId)}</span> to{' '}- <span className="text-foreground">{getRoleNameById(selectedMember?.newRoleId)}</span>- </p>- <p className="mt-3 text-sm text-foreground">- By changing the role of this member their permissions will change.- </p>- </Modal.Content>- <Modal.Separator />- <Modal.Content className="flex gap-3">- <Button- type="default"- block- size="medium"- onClick={() => setUserRoleChangeModalVisible(false)}- >- Cancel- </Button>- <Button- block- type="warning"- size="medium"- disabled={isLoading}- loading={isLoading}- onClick={() => handleRoleChange()}- >- Confirm- </Button>- </Modal.Content>- </Modal></>)}diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/RolesHelperModal/RolesHelperModal.constants.ts b/apps/studio/components/interfaces/Organization/TeamSettings/RolesHelperModal/RolesHelperModal.constants.tsdeleted file mode 100644index 6f2a5189fe9..00000000000--- a/apps/studio/components/interfaces/Organization/TeamSettings/RolesHelperModal/RolesHelperModal.constants.ts+++ /dev/null@@ -1,739 +0,0 @@-const ORGANIZATIONS_PERMISSIONS = {- title: 'Organization',- actions: [- {- description: 'Can change organization name',- permissions: {- owner: true,- admin: false,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can delete organization',- permissions: {- owner: true,- admin: false,- developer: false,- read_only: false,- billing_only: false,- },- },- ],-}--const MEMBERS_MANAGEMENT_PERMISSIONS = {- title: 'Members',- actions: [- {- description: 'Can add an Owner',- permissions: {- owner: true,- admin: false,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can remove an Owner',- permissions: {- owner: true,- admin: false,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can add an Adminstrator',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can remove an Administrator',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can add a Developer',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can remove a Developer',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can revoke an invite',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can resend an invite',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- ],-}--const BILLING_PERMISSIONS = {- title: 'Billing',- actions: [- {- description: 'Can read invoices',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: true,- },- },- {- description: 'Can read billing email',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: true,- },- },- {- description: 'Can change billing email',- permissions: {- owner: true,- admin: false,- developer: false,- read_only: false,- billing_only: true,- },- },- {- description: 'Can view subscription',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: true,- },- },- {- description: 'Can update subscription',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: true,- },- },- {- description: 'Can read billing address',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: true,- },- },- {- description: 'Can update billing address',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: true,- },- },- {- description: 'Can read tax codes',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: true,- },- },- {- description: 'Can update tax codes',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: true,- },- },- {- description: 'Can read payment methods',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: true,- },- },- {- description: 'Can update payment methods',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: true,- },- },- ],-}--const PROJECT_PERMISSIONS = {- title: 'Projects',- actions: [- {- description: 'Can view projects',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create a project',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can delete a project',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can update a project',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can pause a project',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can resume a project',- permissions: {- owner: true,- admin: true,- developer: false,- read_only: false,- billing_only: false,- },- },- {- description: 'Can restart a project',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read API anon keys',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can read API secret keys',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read JWT secret',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can generate new JWT secret',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can update API settings',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- ],-}--const DATABASE_PERMISSIONS = {- title: 'Database',- actions: [- {- description: 'Can read tables',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create/update/delete tables',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read RLS policies',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can read create/update/delete RLS policies',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read database extensions',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can read update database extensions',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read scheduled database backups',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can trigger a scheduled database backup',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read PITR database backups',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can trigger a PITR database backup',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read database publications',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can update database publications',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read database triggers',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create/update/delete database triggers',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read database functions',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create/update/delete database functions',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read database webhooks',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create/update/delete database webhooks',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- ],-}--const SQL_EDITOR_PERMISSIONS = {- title: 'SQL Editor',- actions: [- {- description: 'Can run a SELECT-based query',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can run all other types of queries',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can create/update/delete queries',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- ],-}--const STORAGE_PERMISSIONS = {- title: 'Storage',- actions: [- {- description: 'Can access storage',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- ],-}--const AUTHENTICATION_PERMISSIONS = {- title: 'Authentication',- actions: [- {- description: 'Can view users',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can remove users',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can invite users',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can read authentication settings',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can update authentication settings',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- {- description: 'Can view authentication logs',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- ],-}--const EDGE_FUNCTIONS_PERMISSIONS = {- title: 'Edge Functions',- actions: [- {- description: 'Can view edge functions',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- ],-}--const LOGS_EXPLORER_PERMISSIONS = {- title: 'Logs Explorer',- actions: [- {- description: 'Can view logs explorer',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create queries in the logs explorer',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- ],-}--const REPORTS_PERMISSIONS = {- title: 'Reports',- actions: [- {- description: 'Can view reports',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: true,- billing_only: false,- },- },- {- description: 'Can create/update a report',- permissions: {- owner: true,- admin: true,- developer: true,- read_only: false,- billing_only: false,- },- },- ],-}--export const PERMISSIONS_MAPPING = [- ORGANIZATIONS_PERMISSIONS,- MEMBERS_MANAGEMENT_PERMISSIONS,- BILLING_PERMISSIONS,- PROJECT_PERMISSIONS,- DATABASE_PERMISSIONS,- SQL_EDITOR_PERMISSIONS,- STORAGE_PERMISSIONS,- AUTHENTICATION_PERMISSIONS,- EDGE_FUNCTIONS_PERMISSIONS,- LOGS_EXPLORER_PERMISSIONS,- REPORTS_PERMISSIONS,-]diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/RolesHelperModal/RolesHelperModal.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/RolesHelperModal/RolesHelperModal.tsxdeleted file mode 100644index dcc77f1e4a1..00000000000--- a/apps/studio/components/interfaces/Organization/TeamSettings/RolesHelperModal/RolesHelperModal.tsx+++ /dev/null@@ -1,107 +0,0 @@-import * as Tooltip from '@radix-ui/react-tooltip'-import { Fragment, useState } from 'react'-import { IconCheck, IconHelpCircle, IconInfo, Modal } from 'ui'--import { PERMISSIONS_MAPPING } from './RolesHelperModal.constants'--const RolesHelperModal = () => {- const [showModal, setShowModal] = useState(false)-- const permissionColumnClassName = 'w-[40%] text-sm pl-4 font-bold'- const roleColumnClassName =- 'w-[12%] text-sm h-8 flex items-center justify-center border-l border-control font-bold'-- const accessTooltip = (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <IconInfo size={14} strokeWidth={2} />- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content side="top">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">Only available in Team/Enterprise plan.</span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>- )-- return (- <>- <IconHelpCircle- size={16}- strokeWidth={1.5}- className="cursor-pointer transition hover:text-foreground"- onClick={() => setShowModal(!showModal)}- />- <Modal- closable- hideFooter- visible={showModal}- size={'xxlarge'}- header="Permissions for each role"- onCancel={() => setShowModal(!showModal)}- >- <Modal.Content>- <p className="text-sm">- The following table shows the corresponding permissions for each available role in the- dashboard.- </p>- </Modal.Content>- <Modal.Content>- <div className="rounded border border-default bg-surface-200">- <div className="flex items-center border-b border-control">- <div className={permissionColumnClassName}>Permissions</div>- <div className={roleColumnClassName}>Owner</div>- <div className={roleColumnClassName}>Administrator</div>- <div className={roleColumnClassName}>Developer</div>- <div className={roleColumnClassName}>Read-only {accessTooltip}</div>- <div className={roleColumnClassName}>Billing-only {accessTooltip}</div>- </div>-- <div className="max-h-[425px] overflow-y-auto">- {PERMISSIONS_MAPPING.map((group) => (- <Fragment key={group.title}>- <div className="flex items-center border-b border-control py-2 px-4 last:border-none">- <div className="w-[100%] text-sm">{group.title}</div>- </div>- {group.actions.map((action, idx) => (- <div- key={`${group.title}-${idx}`}- className="flex items-center border-b border-control bg-overlay-hover last:border-none"- >- <div className={permissionColumnClassName}>{action.description}</div>- <div className={roleColumnClassName}>- {action.permissions.owner && <IconCheck size={14} strokeWidth={2} />}- </div>- <div className={roleColumnClassName}>- {action.permissions.admin && <IconCheck size={14} strokeWidth={2} />}- </div>- <div className={roleColumnClassName}>- {action.permissions.developer && <IconCheck size={14} strokeWidth={2} />}- </div>- <div className={roleColumnClassName}>- {action.permissions.read_only && <IconCheck size={14} strokeWidth={2} />}- </div>- <div className={roleColumnClassName}>- {action.permissions.billing_only && <IconCheck size={14} strokeWidth={2} />}- </div>- </div>- ))}- </Fragment>- ))}- </div>- </div>- </Modal.Content>- </Modal>- </>- )-}--export default RolesHelperModaldiff --git a/apps/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsxindex 1274896d030..8ee1bbb4979 100644--- a/apps/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx+++ b/apps/studio/components/interfaces/Organization/TeamSettings/TeamSettings.tsx@@ -1,4 +1,3 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { Search } from 'lucide-react'import { useState } from 'react'import toast from 'react-hot-toast'@@ -11,15 +10,16 @@ import {ScaffoldFilterAndContent,ScaffoldSectionContent,} from 'components/layouts/Scaffold'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useOrganizationMemberDeleteMutation } from 'data/organizations/organization-member-delete-mutation'import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'import { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'import { usePermissionsQuery } from 'data/permissions/permissions-query'import { useIsFeatureEnabled, useSelectedOrganization } from 'hooks'import { useProfile } from 'lib/profile'-import { Button, Input } from 'ui'+import { Input } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'-import InviteMemberButton from './InviteMemberButton'+import { InviteMemberButton } from './InviteMemberButton'import MembersView from './MembersView'import { hasMultipleOwners, useGetRolesManagementPermissions } from './TeamSettings.utils'@@ -92,50 +92,25 @@ const TeamSettings = () => {{organizationMembersCreationEnabled &&canAddMembers &&profile !== undefined &&- selectedOrganization !== undefined && (- <div>- <InviteMemberButton- orgId={selectedOrganization.id}- userId={profile.id}- members={members ?? []}- roles={roles}- rolesAddable={rolesAddable}- />- </div>- )}+ selectedOrganization !== undefined && <InviteMemberButton />}{/* if organizationMembersDeletionEnabled is false, you also can't delete yourself */}{organizationMembersDeletionEnabled && (- <div>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="default"- disabled={!canLeave}- onClick={() => setIsLeaveTeamModalOpen(true)}- loading={isLeaving}- >- Leave team- </Button>- </Tooltip.Trigger>- {!canLeave && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- An organization requires at least 1 owner- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>- </div>+ <>+ <ButtonTooltip+ type="default"+ loading={isLeaving}+ disabled={!canLeave}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canLeave ? 'An organization requires at least 1 owner' : undefined,+ },+ }}+ onClick={() => setIsLeaveTeamModalOpen(true)}+ >+ Leave team+ </ButtonTooltip>+ </>)}</ScaffoldActionsGroup></ScaffoldActionsContainer>diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/RolesAccessMatrix.constants.ts b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/RolesAccessMatrix.constants.tsnew file mode 100644index 00000000000..23ab8dc132a--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/RolesAccessMatrix.constants.ts@@ -0,0 +1,41 @@+// [Joshen] Directly from supabase/apps/docs/content/guides/platform/access-control.mdx+// We could put this into shared-data repository to ensure www and dashboard stays in sync++export const ROLES_ACCESS_MARKDOWN = `+| Permissions | Owner | Administrator | Developer | Read only [^1] |+| ------------------------ | --------------| --------------- | ----------| ----------|+| **Organization** |+| Change organization name | ✓ | | | |+| Delete organization | ✓ | | | |+| **Members** |+| Add an Owner | ✓ | | | |+| Remove an Owner | ✓ | | | |+| Add an Administrator | ✓ | ✓ | | |+| Remove an Administrator | ✓ | ✓ | | |+| Add a Developer | ✓ | ✓ | | |+| Remove a Developer | ✓ | ✓ | | |+| Revoke an invite | ✓ | ✓ | | |+| Resend an invite | ✓ | ✓ | | |+| Accept an invite [^2] | ✓ | ✓ | ✓ |+| **Billing** |+| Read invoices | ✓ | ✓ | ✓ | |+| Read billing email | ✓ | ✓ | ✓ | |+| Change billing email | ✓ | | | |+| View subscription | ✓ | ✓ | ✓ | |+| Update subscription | ✓ | ✓ | | |+| Read billing address | ✓ | ✓ | ✓ | |+| Update billing address | ✓ | ✓ | | |+| Read tax codes | ✓ | ✓ | ✓ | |+| Update tax codes | ✓ | ✓ | | |+| Read payment methods | ✓ | ✓ | ✓ | |+| Update payment methods | ✓ | ✓ | | |+| **Projects** |+| Create a project | ✓ | ✓ | | |+| Delete a project | ✓ | ✓ | | |+| Update a project | ✓ | ✓ | | |+| Pause a project | ✓ | ✓ | | |+| Resume a project | ✓ | ✓ | | |+| Restart a project | ✓ | ✓ | ✓ | |+| Manage tables | ✓ | ✓ | ✓ | |+| View Data | ✓ | ✓ | ✓ | ✓[^3] |+`.trim()diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/RolesAccessMatrix.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/RolesAccessMatrix.tsxnew file mode 100644index 00000000000..705fa4bcb55--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/RolesAccessMatrix.tsx@@ -0,0 +1,117 @@+import { Markdown } from 'components/interfaces/Markdown'+import Table from 'components/to-be-cleaned/Table'+import { ExternalLink } from 'lucide-react'+import { Button, SheetHeader, cn } from 'ui'+import { ROLES_ACCESS_MARKDOWN } from './RolesAccessMatrix.constants'++interface RolesAccessMatrixProps {+ visible: boolean+}++// [Joshen] TODO We'll need to update this for project level permissions too+export const RolesAccessMatrix = ({ visible }: RolesAccessMatrixProps) => {+ return (+ <div+ className={cn(+ 'flex flex-col border-l shadow-[rgba(0,0,0,0.13)_-4px_0px_6px_0px] z-10 bg-studio',+ visible && 'w-[52%]'+ )}+ >+ <SheetHeader className="flex items-center justify-between py-3 border-b">+ <p>Permissions across roles</p>+ <Button asChild type="default" icon={<ExternalLink size={14} />}>+ <a+ href="https://supabase.com/docs/guides/platform/access-control"+ target="_blank"+ rel="noreferrer"+ >+ Documentation+ </a>+ </Button>+ </SheetHeader>++ <div className="flex flex-col flex-grow gap-y-4 px-5 py-5 overflow-y-auto">+ <p className="text-sm text-foreground-light">+ The table below shows the corresponding permissions for each available role you can assign+ a team member in the Dashboard.+ </p>+ <Markdown+ content={ROLES_ACCESS_MARKDOWN}+ className="max-w-full [&>table>thead>tr>th:not(:first-child)]:text-center [&>table>tbody>tr>td:not(:first-child)]:text-center"+ components={{+ th: ({ children }) => {+ if (children?.[0] && typeof children[0] === 'string' && children[0].includes('[^')) {+ const text = children[0].split('[^')+ const number = text?.[1]?.[0] ?? undefined+ return (+ <th>+ {text[0]}+ {number !== undefined && (+ <sup+ tabIndex={Number(number)}+ className="ml-0.5 text-foreground cursor-pointer underline"+ onClick={() => {+ const el = document.getElementById(`roles-helper-${number}`)+ if (el !== undefined)+ el?.scrollIntoView({ behavior: 'smooth', block: 'center' })+ }}+ >+ {number}+ </sup>+ )}+ </th>+ )+ } else {+ return <th>{children?.[0]}</th>+ }+ },+ td: ({ children }) => {+ if (children?.[0] && typeof children[0] === 'string' && children[0].includes('[^')) {+ const text = children[0].split('[^')+ const number = text?.[1]?.[0] ?? undefined+ return (+ <td>+ {text[0]}+ {number !== undefined && (+ <sup+ tabIndex={Number(number)}+ className="ml-0.5 text-foreground cursor-pointer underline"+ onClick={() => {+ const el = document.getElementById(`roles-helper-${number}`)+ if (el !== undefined)+ el?.scrollIntoView({ behavior: 'smooth', block: 'center' })+ }}+ >+ {number}+ </sup>+ )}+ </td>+ )+ } else {+ return <td>{children?.[0]}</td>+ }+ },+ }}+ />++ <div className="flex flex-col gap-y-2">+ <p className="text-sm">Footnotes</p>+ <ol className="list-decimal pl-6 text-xs flex flex-col gap-y-2">+ <li id="roles-helper-1">Available on the Teams and Enterprise Plans.</li>+ <li id="roles-helper-2">+ Invites sent from a SSO account can only be accepted by another SSO account coming+ from the same identity provider. This is a security measure that prevents accidental+ invites to accounts not managed by your company's enterprise systems+ </li>+ <li id="roles-helper-3">+ <Markdown+ className="text-xs text-foreground"+ content="Only available on projects using PostgreSQL 14 and above. You can upgrade your project through [infrastructure settings](https://supabase.com/dashboard/project/_/settings/infrastructure)."+ />+ </li>+ </ol>+ </div>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesConfirmationModal.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesConfirmationModal.tsxnew file mode 100644index 00000000000..e40fccec929--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesConfirmationModal.tsx@@ -0,0 +1,239 @@+import { useQueryClient } from '@tanstack/react-query'+import { useState } from 'react'+import toast from 'react-hot-toast'++import { useParams } from 'common'+import { organizationKeys } from 'data/organization-members/keys'+import { useOrganizationMemberAssignRoleMutation } from 'data/organization-members/organization-member-role-assign-mutation'+import { useOrganizationMemberUnassignRoleMutation } from 'data/organization-members/organization-member-role-unassign-mutation'+import { useOrganizationMemberUpdateRoleMutation } from 'data/organization-members/organization-member-role-update-mutation'+import {+ OrganizationRole,+ useOrganizationRolesV2Query,+} from 'data/organization-members/organization-roles-query'+import { organizationKeys as organizationKeysV1 } from 'data/organizations/keys'+import { OrganizationMember } from 'data/organizations/organization-members-query'+import { useProjectsQuery } from 'data/projects/projects-query'+import { useSelectedOrganization } from 'hooks'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import {+ ProjectRoleConfiguration,+ deriveChanges,+ deriveRoleChangeActions,+ formatMemberRoleToProjectRoleConfiguration,+} from './UpdateRolesPanel.utils'++interface UpdateRolesConfirmationModal {+ visible: boolean+ member: OrganizationMember+ projectsRoleConfiguration: ProjectRoleConfiguration[]+ onClose: (success?: boolean) => void+}++export const UpdateRolesConfirmationModal = ({+ visible,+ member,+ projectsRoleConfiguration,+ onClose,+}: UpdateRolesConfirmationModal) => {+ const { slug } = useParams()+ const queryClient = useQueryClient()+ const organization = useSelectedOrganization()+ const { data: projects } = useProjectsQuery()+ const { data: allRoles } = useOrganizationRolesV2Query({ slug: organization?.slug })++ // [Joshen] Separate saving state instead of using RQ due to several successive steps+ const [saving, setSaving] = useState(false)+ const { mutateAsync: assignRole } = useOrganizationMemberAssignRoleMutation()+ const { mutateAsync: removeRole } = useOrganizationMemberUnassignRoleMutation({+ onError: () => {},+ })+ const { mutateAsync: updateRole } = useOrganizationMemberUpdateRoleMutation()++ const availableRoles = allRoles?.org_scoped_roles ?? []+ const { org_scoped_roles, project_scoped_roles } = allRoles ?? {+ org_scoped_roles: [],+ project_scoped_roles: [],+ }+ const orgProjects = (projects ?? []).filter((p) => p.organization_id === organization?.id)+ const originalConfiguration =+ allRoles !== undefined+ ? formatMemberRoleToProjectRoleConfiguration(member, allRoles, projects ?? [])+ : []+ const changesToRoles = deriveChanges(+ originalConfiguration,+ projectsRoleConfiguration,+ projects ?? []+ )++ const onConfirmUpdateMemberRoles = async () => {+ if (slug === undefined) return console.error('Slug is required')++ setSaving(true)+ const gotrueId = member.gotrue_id+ const existingRoles = member.role_ids+ .map((id) => {+ return [...org_scoped_roles, ...project_scoped_roles].find((r) => r.id === id)+ })+ .filter(Boolean) as OrganizationRole[]+ const isChangeWithinOrgScope =+ projectsRoleConfiguration.length === 1 && projectsRoleConfiguration[0].ref === undefined++ // Early return if we're just updating org level roles+ // Everything else below is just project level role changes then+ if (isChangeWithinOrgScope) {+ try {+ await assignRole({+ slug,+ gotrueId,+ roleId: projectsRoleConfiguration[0].roleId,+ })+ toast.success(`Successfully updated role for ${member.username}`)+ onClose(true)+ return+ } catch (error: any) {+ setSaving(false)+ return toast.error(`Failed to update role: ${error.message}`)+ }+ }++ const { toRemove, toAssign, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)++ try {+ await Promise.all([+ ...toAssign.map(({ roleId, projectIds }) =>+ assignRole({+ slug,+ gotrueId,+ roleId,+ projects: projectIds.map((id) => projects?.find((p) => p.id === id)?.ref) as string[],+ })+ ),+ ])+ await Promise.all([+ ...toRemove.map((roleId) => removeRole({ slug, gotrueId, roleId })),+ ...toUpdate.map(({ roleId, projectIds }) =>+ updateRole({+ slug,+ gotrueId,+ roleId,+ roleName: project_scoped_roles.find((r) => r.id === roleId)?.name as string,+ projects: projectIds.map((id) => projects?.find((p) => p.id === id)?.ref) as string[],+ })+ ),+ ])++ await Promise.all([+ queryClient.invalidateQueries(organizationKeys.rolesV2(slug)),+ queryClient.invalidateQueries(organizationKeysV1.members(slug)),+ ])+ toast.success(`Successfully updated role for ${member.username}`)+ onClose(true)+ } catch (error: any) {+ setSaving(false)+ return toast.error(`Failed to update role: ${error.message}`)+ }+ }++ return (+ <ConfirmationModal+ size="medium"+ visible={visible}+ loading={saving}+ title="Confirm to change roles of member"+ confirmLabel="Update roles"+ confirmLabelLoading="Updating"+ onCancel={() => onClose()}+ onConfirm={onConfirmUpdateMemberRoles}+ >+ <div className="flex flex-col gap-y-3">+ <p className="text-sm text-foreground-light">+ You are making the following changes to the role of{' '}+ <span className="text-foreground">{member.username}</span> in the organization{' '}+ <span className="text-foreground">{organization?.name}</span>:+ </p>+ <div className="flex flex-col gap-y-2">+ {changesToRoles.removed.length !== 0 && (+ <div>+ <p className="text-sm">+ Removing {changesToRoles.removed.length} role+ {changesToRoles.removed.length > 1 ? 's' : ''} for user:+ </p>+ <ul className="list-disc pl-6">+ {changesToRoles.removed.map((x, i) => {+ const role =+ org_scoped_roles.find((y) => y.id === x.roleId) ??+ project_scoped_roles.find((y) => y.id === x.roleId)+ const project = orgProjects.find((y) => y.ref === x.ref)+ const roleName = (role?.name ?? 'Unknown').split('_')[0]++ return (+ <li key={`update-${i}`} className="text-sm text-foreground-light">+ <span className="text-foreground">{roleName}</span> on{' '}+ <span className={project !== undefined ? 'text-foreground' : ''}>+ {project?.name ?? 'organization'}+ </span>+ </li>+ )+ })}+ </ul>+ </div>+ )}+ {changesToRoles.added.length !== 0 && (+ <div>+ <p className="text-sm">+ Adding {changesToRoles.added.length} role+ {changesToRoles.added.length > 1 ? 's' : ''} for user:+ </p>+ <ul className="list-disc pl-6">+ {changesToRoles.added.map((x, i) => {+ const role = availableRoles.find((y) => y.id === x.roleId)+ const project = orgProjects.find((y) => y.ref === x.ref)+ return (+ <li key={`update-${i}`} className="text-sm text-foreground-light">+ <span className="text-foreground">{role?.name}</span> on{' '}+ <span className={project !== undefined ? 'text-foreground' : ''}>+ {project?.name ?? 'organization'}+ </span>+ </li>+ )+ })}+ </ul>+ </div>+ )}+ {changesToRoles.updated.length !== 0 && (+ <div>+ <p className="text-sm">+ Updating {changesToRoles.updated.length} role+ {changesToRoles.updated.length > 1 ? 's' : ''} for user:+ </p>+ <ul className="list-disc pl-6">+ {changesToRoles.updated.map((x, i) => {+ const originalRole =+ org_scoped_roles.find((y) => y.id === x.originalRole) ??+ project_scoped_roles.find((y) => y.id === x.originalRole)+ const updatedRole = org_scoped_roles.find((y) => y.id === x.updatedRole)+ const project = orgProjects.find((y) => y.ref === x.ref)+ const originalRoleName = (originalRole?.name ?? 'Unknown').split('_')[0]++ return (+ <li key={`update-${i}`} className="text-sm text-foreground-light">+ From <span className="text-foreground">{originalRoleName}</span> to{' '}+ <span className="text-foreground">{updatedRole?.name}</span> on{' '}+ <span className={project !== undefined ? 'text-foreground' : ''}>+ {project?.name ?? 'organization'}+ </span>+ </li>+ )+ })}+ </ul>+ </div>+ )}+ </div>+ <p className="text-sm text-foreground">+ By changing the role of this member their permissions will change.+ </p>+ </div>+ </ConfirmationModal>+ )+}diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.tsxnew file mode 100644index 00000000000..7b78dd35ef2--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.tsx@@ -0,0 +1,417 @@+import { isEqual } from 'lodash'+import { PanelLeftClose, PanelRightClose, X } from 'lucide-react'+import { useEffect, useState } from 'react'++import { useParams } from 'common'+import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'+import { OrganizationMember } from 'data/organizations/organization-members-query'+import { usePermissionsQuery } from 'data/permissions/permissions-query'+import { useProjectsQuery } from 'data/projects/projects-query'+import { useFlag, useSelectedOrganization } from 'hooks'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ CommandEmpty_Shadcn_,+ CommandGroup_Shadcn_,+ CommandInput_Shadcn_,+ CommandItem_Shadcn_,+ CommandList_Shadcn_,+ Command_Shadcn_,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Popover_Shadcn_,+ ScrollArea,+ SelectContent_Shadcn_,+ SelectGroup_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ Select_Shadcn_,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetSection,+ Switch,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+ cn,+} from 'ui'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'+import { useGetRolesManagementPermissions } from '../TeamSettings.utils'+import { RolesAccessMatrix } from './RolesAccessMatrix'+import { UpdateRolesConfirmationModal } from './UpdateRolesConfirmationModal'+import {+ ProjectRoleConfiguration,+ formatMemberRoleToProjectRoleConfiguration,+} from './UpdateRolesPanel.utils'+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'++interface UpdateRolesPanelProps {+ visible: boolean+ member: OrganizationMember+ onClose: () => void+}++export const UpdateRolesPanel = ({ visible, member, onClose }: UpdateRolesPanelProps) => {+ const { slug } = useParams()+ const organization = useSelectedOrganization()+ const projectLevelPermissionsEnabled = useFlag('projectLevelPermissions')++ const { data: projects } = useProjectsQuery()+ const { data: permissions } = usePermissionsQuery()+ const { data: allRoles, isSuccess: isSuccessRoles } = useOrganizationRolesV2Query({ slug })+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: slug })++ // [Joshen] We use the org scoped roles as the source for available roles+ const orgScopedRoles = allRoles?.org_scoped_roles ?? []+ const projectScopedRoles = allRoles?.project_scoped_roles ?? []+ const isEnterprise = subscription?.plan.id === 'enterprise'++ const { rolesAddable, rolesRemovable } = useGetRolesManagementPermissions(+ organization?.id,+ orgScopedRoles.concat(projectScopedRoles),+ permissions ?? []+ )+ const cannotAddAnyRoles = orgScopedRoles.every((r) => !rolesAddable.includes(r.id))++ const [showConfirmation, setShowConfirmation] = useState(false)+ const [showProjectDropdown, setShowProjectDropdown] = useState(false)+ const [showRolesAccessMatrix, setShowRolesAccessMatrix] = useState(false)+ const [projectsRoleConfiguration, setProjectsRoleConfiguration] = useState<+ ProjectRoleConfiguration[]+ >([])++ const originalConfiguration =+ allRoles !== undefined+ ? formatMemberRoleToProjectRoleConfiguration(member, allRoles, projects ?? [])+ : []+ const orgProjects = (projects ?? []).filter((p) => p.organization_id === organization?.id)+ const isApplyingRoleToAllProjects =+ projectsRoleConfiguration.length === 1 && projectsRoleConfiguration[0]?.ref === undefined+ const canSaveRoles = projectsRoleConfiguration.length > 0++ const lowerPermissionsRole = orgScopedRoles.find((r) => r.name === 'Developer')?.id+ const sortByObject: any = ['Owner', 'Administrator', 'Developer'].reduce((obj, item, index) => {+ return { ...obj, [item]: index }+ }, {})+ const noAccessProjects = orgProjects.filter((project) => {+ return !projectsRoleConfiguration.some((p) => p.ref === project.ref)+ })+ const numberOfProjectsWithAccess = orgProjects.length - noAccessProjects.length+ const numberOfAccessHasChanges = originalConfiguration.length !== noAccessProjects.length++ const onSelectProject = (ref: string) => {+ setProjectsRoleConfiguration(+ projectsRoleConfiguration.concat({+ ref,+ roleId: lowerPermissionsRole ?? orgScopedRoles[0].id,+ })+ )+ setShowProjectDropdown(false)+ }++ const onRemoveProject = (ref?: string) => {+ if (ref === undefined) return+ setProjectsRoleConfiguration(projectsRoleConfiguration.filter((p) => p.ref !== ref))+ }++ const onSelectRole = (value: string, project: ProjectRoleConfiguration) => {+ if (project.ref !== undefined) {+ setProjectsRoleConfiguration(+ projectsRoleConfiguration.map((p) => {+ if (p.ref === project.ref) {+ return { ref: p.ref, projectId: p.projectId, roleId: Number(value) }+ } else {+ return p+ }+ })+ )+ } else {+ setProjectsRoleConfiguration([{ ref: undefined, roleId: Number(value) }])+ }+ }++ const onToggleApplyToAllProjects = () => {+ const roleIdToApply =+ projectsRoleConfiguration[0]?.roleId ?? lowerPermissionsRole ?? orgScopedRoles[0].id+ if (isApplyingRoleToAllProjects) {+ setProjectsRoleConfiguration(+ orgProjects.map((p) => {+ return { ref: p.ref, projectId: p.id, roleId: roleIdToApply }+ })+ )+ } else {+ setProjectsRoleConfiguration([{ ref: undefined, roleId: roleIdToApply }])+ }+ }++ useEffect(() => {+ if (visible && isSuccessRoles) {+ const roleConfiguration = formatMemberRoleToProjectRoleConfiguration(+ member,+ allRoles,+ projects ?? []+ )+ setProjectsRoleConfiguration(roleConfiguration)+ } else {+ setShowRolesAccessMatrix(false)+ }+ }, [visible, isSuccessRoles])++ return (+ <>+ <Sheet open={visible} onOpenChange={() => onClose()}>+ <SheetContent+ showClose={false}+ size={showRolesAccessMatrix ? 'lg' : 'default'}+ className={cn(+ 'bg-surface-200 p-0 flex flex-row gap-0',+ showRolesAccessMatrix ? '!min-w-[1000px]' : '!min-w-[400px]'+ )}+ >+ <div className={cn('flex flex-col grow', showRolesAccessMatrix ? 'w-[48%]' : 'w-full')}>+ <SheetHeader+ className={cn('py-3 flex flex-row justify-between gap-x-4 items-center border-b')}+ >+ <p className="truncate" title={`Manage access for ${member.username}`}>+ Manage access for {member.username}+ </p>+ <Tooltip_Shadcn_ delayDuration={100}>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="outline"+ className="[&>div]:text-foreground-light px-1.5"+ icon={!showRolesAccessMatrix ? <PanelLeftClose /> : <PanelRightClose />}+ onClick={() => setShowRolesAccessMatrix(!showRolesAccessMatrix)}+ />+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="left">+ {showRolesAccessMatrix ? 'Hide' : 'Show'} role permissions+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </SheetHeader>++ <SheetSection className="h-full overflow-auto flex flex-col gap-y-4">+ {projectLevelPermissionsEnabled && isEnterprise && (+ <div className="flex items-center gap-x-4">+ <Switch+ disabled={cannotAddAnyRoles}+ checked={isApplyingRoleToAllProjects}+ onCheckedChange={onToggleApplyToAllProjects}+ />+ <p className="text-sm">Apply roles to all projects in the organization</p>+ </div>+ )}++ {projectsRoleConfiguration.length === 0 && (+ <Alert_Shadcn_>+ <WarningIcon />+ <AlertTitle_Shadcn_>+ Team members need to be assigned at least one role+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ You may not remove all roles from a team member+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ {!isApplyingRoleToAllProjects &&+ projectsRoleConfiguration.length > 0 &&+ projectsRoleConfiguration.length !== orgProjects.length && (+ <Alert_Shadcn_>+ <AlertTitle_Shadcn_>+ {numberOfAccessHasChanges+ ? `This member will only have access to ${numberOfProjectsWithAccess} project${numberOfProjectsWithAccess > 1 ? 's' : ''}`+ : `This member only has access to ${numberOfProjectsWithAccess} project${numberOfProjectsWithAccess > 1 ? 's' : ''}`}+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ {member.username} {numberOfAccessHasChanges ? 'will' : 'does'} not have access+ to the following {noAccessProjects.length} project+ {noAccessProjects.length > 1 ? 's' : ''}:+ <ul className="list-disc pl-6">+ {noAccessProjects.map((project) => {+ return <li key={project.id}>{project.name}</li>+ })}+ </ul>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ <div className="flex flex-col gap-y-2">+ {projectsRoleConfiguration+ .sort((a, b) => (a?.projectId ?? 0) - (b?.projectId ?? 0))+ .map((project) => {+ const name =+ project.ref === undefined+ ? 'All projects'+ : projects?.find((p) => p.ref === project.ref)?.name+ const role = orgScopedRoles.find((r) => {+ if (project.baseRoleId !== undefined) return r.id === project.baseRoleId+ else return r.id === project.roleId+ })+ const canRemoveRole = rolesRemovable.includes(role?.id ?? 0)++ return (+ <div+ key={`${project.ref}-${project.roleId}`}+ className="flex items-center justify-between"+ >+ <p className="text-sm">{name}</p>++ <div className="flex items-center gap-x-2">+ {cannotAddAnyRoles ? (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <div className="flex items-center justify-between rounded-md border border-button bg-button px-3 py-2 text-sm h-10 w-56 text-foreground-light">+ {role?.name ?? 'Unknown'}+ </div>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">+ Additional permissions required to update role+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ ) : (+ <Select_Shadcn_+ value={(project?.baseRoleId ?? project.roleId).toString()}+ onValueChange={(value) => onSelectRole(value, project)}+ >+ <SelectTrigger_Shadcn_+ className={cn(+ 'text-sm h-10 w-56',+ role?.name === undefined && 'text-foreground-light'+ )}+ >+ {role?.name ?? 'Please select a role'}+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {(orgScopedRoles ?? [])+ .sort((a, b) => sortByObject[a.name] - sortByObject[b.name])+ .map((role) => {+ const canAssignRole = rolesAddable.includes(role.id)++ return (+ <SelectItem_Shadcn_+ key={role.id}+ value={role.id.toString()}+ className="text-sm"+ disabled={!canAssignRole}+ >+ {role.name}+ </SelectItem_Shadcn_>+ )+ })}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ )}++ {!isApplyingRoleToAllProjects && (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="text"+ disabled={!canRemoveRole}+ className="px-1"+ icon={<X size={14} />}+ onClick={() => onRemoveProject(project?.ref)}+ />+ </TooltipTrigger_Shadcn_>+ {!canRemoveRole && (+ <TooltipContent_Shadcn_ side="bottom">+ Additional permission required to remove role from member+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_>+ )}+ </div>+ </div>+ )+ })}+ </div>++ {!isApplyingRoleToAllProjects && (+ <Popover_Shadcn_+ open={showProjectDropdown}+ onOpenChange={setShowProjectDropdown}+ modal={false}+ >+ <PopoverTrigger_Shadcn_ asChild>+ <Button type="default" className="w-min">+ Assign role to project+ </Button>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">+ <Command_Shadcn_>+ <CommandInput_Shadcn_ placeholder="Find project..." />+ <CommandList_Shadcn_>+ <CommandEmpty_Shadcn_>No projects found</CommandEmpty_Shadcn_>+ <CommandGroup_Shadcn_>+ <ScrollArea className={(projects || []).length > 7 ? 'h-[210px]' : ''}>+ {orgProjects.map((project) => {+ const hasRoleAssigned = projectsRoleConfiguration.some(+ (p) => p.ref === project.ref+ )+ return (+ <CommandItem_Shadcn_+ key={project.ref}+ disabled={hasRoleAssigned}+ className="cursor-pointer w-full justify-between"+ onSelect={() => onSelectProject(project.ref)}+ onClick={() => onSelectProject(project.ref)}+ >+ <p className="truncate">{project.name}</p>+ {hasRoleAssigned && (+ <p className="w-[45%] text-right">Already assigned</p>+ )}+ </CommandItem_Shadcn_>+ )+ })}+ </ScrollArea>+ </CommandGroup_Shadcn_>+ </CommandList_Shadcn_>+ </Command_Shadcn_>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ )}+ </SheetSection>++ <SheetFooter className="flex items-center !justify-end px-5 py-4 w-full border-t">+ <Button type="default" disabled={false} onClick={() => onClose()}>+ Cancel+ </Button>+ <Button+ loading={false}+ disabled={!canSaveRoles}+ onClick={() => {+ if (isEqual(projectsRoleConfiguration, originalConfiguration)) {+ onClose()+ } else {+ setShowConfirmation(true)+ }+ }}+ >+ Save roles+ </Button>+ </SheetFooter>+ </div>++ {showRolesAccessMatrix && <RolesAccessMatrix visible={showRolesAccessMatrix} />}+ </SheetContent>+ </Sheet>++ <UpdateRolesConfirmationModal+ visible={showConfirmation}+ member={member}+ projectsRoleConfiguration={projectsRoleConfiguration}+ onClose={(success) => {+ setShowConfirmation(false)+ if (success) onClose()+ }}+ />+ </>+ )+}diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.utils.test.ts b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.utils.test.tsnew file mode 100644index 00000000000..dfa84b24f85--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.utils.test.ts@@ -0,0 +1,425 @@+import { deriveRoleChangeActions } from './UpdateRolesPanel.utils'++// [Joshen] This is specifically testing the project scope changes+describe('UpdateRolesPanel.utils.ts:deriveRoleChangeActions', () => {+ test('Should update from org scope to project scope correctly', () => {+ const existingRoles = [+ {+ id: 3,+ name: 'Developer',+ description: null,+ project_ids: null,+ base_role_id: 6,+ },+ ]+ const changesToRoles = {+ removed: [],+ added: [+ { projectId: 1, ref: 'ref_1', roleId: 3 },+ { projectId: 2, ref: 'ref_2', roleId: 3 },+ { projectId: 3, ref: 'ref_3', roleId: 3 },+ ],+ updated: [],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toRemove).toStrictEqual([3])+ expect(toAssign).toStrictEqual([{ roleId: 3, projectIds: [1, 2, 3] }])+ expect(toUpdate).toStrictEqual([])+ })+ test('Should update role for a single project (Project 1, Developer to Admin)', () => {+ const existingRoles = [+ {+ id: 29,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1],+ base_role_id: 3,+ },+ ]+ const changesToRoles = {+ removed: [],+ added: [],+ updated: [+ {+ ref: 'ref_1',+ projectId: 1,+ originalRole: 29,+ originalBaseRole: 3,+ updatedRole: 1,+ },+ ],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toRemove).toStrictEqual([29])+ expect(toAssign).toStrictEqual([{ roleId: 1, projectIds: [1] }])+ expect(toUpdate).toStrictEqual([])+ })+ test('Should remove role if role changes completely involve either removing role or updating role to another', () => {+ // Developer of projects 1, 2, 3+ // Remove developer role for projects 1, 2+ // Update developer to admin for project 3+ const existingRoles = [+ {+ id: 29,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1, 2, 3],+ base_role_id: 3,+ },+ ]+ const changesToRoles = {+ removed: [+ {+ ref: 'ref_1',+ projectId: 1,+ roleId: 29,+ baseRoleId: 3,+ },+ {+ ref: 'ref_2',+ projectId: 2,+ roleId: 29,+ baseRoleId: 3,+ },+ ],+ added: [],+ updated: [+ {+ ref: 'ref_3',+ projectId: 3,+ originalRole: 29,+ originalBaseRole: 3,+ updatedRole: 1,+ },+ ],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toRemove).toStrictEqual([29])+ expect(toAssign).toStrictEqual([{ roleId: 1, projectIds: [3] }])+ expect(toUpdate).toStrictEqual([])+ })+ test('Should not remove role if role changes partially involve either removing role or updating role to another', () => {+ const existingRoles = [+ {+ id: 29,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1, 2, 3],+ base_role_id: 3,+ },+ ]+ const changesToRoles = {+ removed: [+ {+ ref: 'ref_1',+ projectId: 1,+ roleId: 29,+ baseRoleId: 3,+ },+ ],+ added: [],+ updated: [+ {+ ref: 'ref_3',+ projectId: 3,+ originalRole: 29,+ originalBaseRole: 3,+ updatedRole: 1,+ },+ ],+ }++ const { toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toRemove).toStrictEqual([])+ expect(toUpdate).toStrictEqual([{ roleId: 29, projectIds: [2] }])+ })+ test('Should update role if newly added role(s) has the same base_role_id, and if removed role has same base_role_id', () => {+ const existingRoles = [+ {+ id: 29,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1, 2, 3],+ base_role_id: 3,+ },+ ]+ const changesToRoles = {+ removed: [+ {+ ref: 'ref_1',+ projectId: 1,+ roleId: 29,+ baseRoleId: 3,+ },+ ],+ added: [+ { projectId: 4, ref: 'ref_2', roleId: 3 },+ { projectId: 5, ref: 'ref_3', roleId: 3 },+ ],+ updated: [],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toUpdate).toStrictEqual([{ roleId: 29, projectIds: [2, 3, 4, 5] }])+ expect(toAssign).toStrictEqual([])+ expect(toRemove).toStrictEqual([])+ })+ test('Should assign new role if newly added role(s) has the no base_role_id as any existing role', () => {+ const existingRoles = [+ {+ id: 29,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1, 2, 3],+ base_role_id: 3,+ },+ ]+ const changesToRoles = {+ removed: [],+ added: [+ { projectId: 4, ref: 'ref_2', roleId: 1 },+ { projectId: 5, ref: 'ref_3', roleId: 1 },+ ],+ updated: [],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toAssign).toStrictEqual([{ roleId: 1, projectIds: [4, 5] }])+ expect(toUpdate).toStrictEqual([])+ expect(toRemove).toStrictEqual([])+ })+ test('Should assign project read only role from org developer role correctly', () => {+ const existingRoles = [+ {+ id: 3,+ name: 'Developer',+ description: null,+ project_ids: null,+ base_role_id: 6,+ },+ ]+ const changesToRoles = {+ removed: [{ projectId: undefined, ref: undefined, roleId: 3 }],+ added: [{ projectId: 1, ref: 'ref_1', roleId: 6 }],+ updated: [],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toAssign).toStrictEqual([{ roleId: 6, projectIds: [1] }])+ expect(toUpdate).toStrictEqual([])+ expect(toRemove).toStrictEqual([3])+ })+ test('Myriad of updates to stress test function logic (I)', () => {+ // Given 6 projects 1, 2, 3, 4, 5, 6+ // Existing has developer role for 1, 2, 3, admin role for 4, owner role for 5+ const existingRoles = [+ {+ id: 30,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1, 2, 3],+ base_role_id: 3, // Developer+ },+ {+ id: 31,+ name: 'Administrator_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [4],+ base_role_id: 1, // Admin,+ },+ {+ id: 32,+ name: 'Owner_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [5],+ base_role_id: 5, // Owner,+ },+ ]++ // Removing developer for 1+ // Updating developer -> admin for 2+ // Updating developer -> owner for 3+ // Updating administrator -> owner for 4+ // Adding administrator for 6+ const changesToRoles = {+ removed: [+ {+ ref: 'ref_1',+ projectId: 1,+ roleId: 30,+ baseRoleId: 3,+ },+ ],+ added: [{ projectId: 6, ref: 'ref_6', roleId: 1 }],+ updated: [+ {+ ref: 'ref_2',+ projectId: 2,+ originalRole: 30,+ originalBaseRole: 3,+ updatedRole: 1,+ },+ {+ ref: 'ref_3',+ projectId: 3,+ originalRole: 30,+ originalBaseRole: 3,+ updatedRole: 5,+ },+ {+ ref: 'ref_4',+ projectId: 4,+ originalRole: 31,+ originalBaseRole: 1,+ updatedRole: 5,+ },+ ],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toAssign).toStrictEqual([])+ expect(toUpdate).toStrictEqual([+ { roleId: 31, projectIds: [2, 6] },+ { roleId: 32, projectIds: [3, 4, 5] },+ ])+ expect(toRemove).toStrictEqual([30])+ })+ test('Myriad of updates to stress test function logic (II)', () => {+ // Given 5 projects 1, 2, 3, 4, 5+ // Existing has developer role for 1, admin role for 2+ const existingRoles = [+ {+ id: 30,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1],+ base_role_id: 3, // Developer+ },+ {+ id: 31,+ name: 'Administrator_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [2],+ base_role_id: 1, // Admin,+ },+ ]++ // Adding developer for 4+ // Updating developer -> admin for 1+ // Updating admin -> developer for 2+ // Adding owner for 5+ const changesToRoles = {+ removed: [],+ added: [+ { projectId: 4, ref: 'ref_4', roleId: 3 },+ { projectId: 5, ref: 'ref_5', roleId: 5 },+ ],+ updated: [+ {+ ref: 'ref_1',+ projectId: 1,+ originalRole: 30,+ originalBaseRole: 3,+ updatedRole: 1,+ },+ {+ ref: 'ref_2',+ projectId: 2,+ originalRole: 31,+ originalBaseRole: 1,+ updatedRole: 3,+ },+ ],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toAssign).toStrictEqual([{ roleId: 5, projectIds: [5] }])+ expect(toUpdate).toStrictEqual([+ { roleId: 30, projectIds: [2, 4] },+ { roleId: 31, projectIds: [1] },+ ])+ expect(toRemove).toStrictEqual([])+ })+ test('Myriad of updates to stress test function logic (III)', () => {+ // Given 10 projects 1, 2, 3, 4, 5, 6, 7, 8, 9, 10+ // Existing has developer role for 1, 2, 3, admin role for 4, 5, 6, owner for 7+ const existingRoles = [+ {+ id: 30,+ name: 'Developer_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [1, 2, 3],+ base_role_id: 3, // Developer+ },+ {+ id: 31,+ name: 'Administrator_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [4, 5, 6],+ base_role_id: 1, // Admin,+ },+ {+ id: 32,+ name: 'Owner_qggwcbikivagivlidfhw',+ description: '',+ project_ids: [7],+ base_role_id: 5, // Owner+ },+ ]++ // Remove access from projects 2, 7+ // Update developer -> owner for project 3+ // Update admin -> owner for project 5+ // Add admin for project 8+ // Add developer for project 9 and 10+ const changesToRoles = {+ removed: [+ {+ ref: 'ref_2',+ projectId: 2,+ roleId: 30,+ baseRoleId: 3,+ },+ {+ ref: 'ref_7',+ projectId: 7,+ roleId: 32,+ baseRoleId: 5,+ },+ ],+ added: [+ { projectId: 8, ref: 'ref_8', roleId: 1 },+ { projectId: 9, ref: 'ref_9', roleId: 3 },+ { projectId: 10, ref: 'ref_10', roleId: 3 },+ ],+ updated: [+ {+ ref: 'ref_3',+ projectId: 3,+ originalRole: 30,+ originalBaseRole: 3,+ updatedRole: 5,+ },+ {+ ref: 'ref_5',+ projectId: 5,+ originalRole: 31,+ originalBaseRole: 1,+ updatedRole: 5,+ },+ ],+ }++ const { toAssign, toRemove, toUpdate } = deriveRoleChangeActions(existingRoles, changesToRoles)+ expect(toAssign).toStrictEqual([])+ expect(toRemove).toStrictEqual([])+ expect(toUpdate).toStrictEqual([+ { roleId: 30, projectIds: [1, 9, 10] },+ { roleId: 31, projectIds: [4, 6, 8] },+ { roleId: 32, projectIds: [3, 5] },+ ])+ })+})diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.utils.ts b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.utils.tsnew file mode 100644index 00000000000..89104c2c2d5--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanel.utils.ts@@ -0,0 +1,184 @@+import { groupBy, isEqual } from 'lodash'++import {+ OrganizationRole,+ OrganizationRolesResponse,+} from 'data/organization-members/organization-roles-query'+import { OrganizationMember } from 'data/organizations/organization-members-query'+import { ProjectInfo } from 'data/projects/projects-query'++export interface ProjectRoleConfiguration {+ ref?: string+ projectId?: number+ roleId: number+ baseRoleId?: number+}++export const formatMemberRoleToProjectRoleConfiguration = (+ member: OrganizationMember,+ allRoles: OrganizationRolesResponse,+ projects: ProjectInfo[]+) => {+ const { org_scoped_roles, project_scoped_roles } = allRoles++ const roleConfiguration = member.role_ids+ .map((id) => {+ const orgRole = org_scoped_roles.find((role) => role.id === id)+ if (orgRole !== undefined) {+ return { ref: undefined, roleId: orgRole.id }+ }+ const projectRole = project_scoped_roles.find((role) => role.id === id)+ if (projectRole !== undefined) {+ const _projects = (projectRole?.project_ids ?? []).map((id) =>+ projects.find((p) => p.id === id)+ )+ return _projects.map((p) => ({+ ref: p?.ref,+ projectId: p?.id,+ roleId: projectRole.id,+ baseRoleId: projectRole.base_role_id,+ }))+ }+ })+ .filter(Boolean)+ .flat() as ProjectRoleConfiguration[]++ return roleConfiguration+}++export const deriveChanges = (+ original: ProjectRoleConfiguration[] = [],+ final: ProjectRoleConfiguration[] = [],+ projects: ProjectInfo[]+) => {+ const removed: ProjectRoleConfiguration[] = []+ const added: ProjectRoleConfiguration[] = []+ const updated: {+ ref?: string+ projectId?: number+ originalRole: number+ originalBaseRole?: number+ updatedRole: number+ }[] = []++ original.forEach((x) => {+ const updatedRoleForProject = final.find((y) => x.ref === y.ref)+ if (updatedRoleForProject === undefined) {+ removed.push(x)+ } else if (updatedRoleForProject.roleId !== x.roleId) {+ updated.push({+ ref: updatedRoleForProject.ref,+ originalRole: x.roleId,+ originalBaseRole: x.baseRoleId,+ updatedRole: updatedRoleForProject.roleId,+ })+ }+ })++ final.forEach((x) => {+ const newRoleForProject = original.find((y) => x.ref === y.ref)+ if (newRoleForProject === undefined) {+ added.push(x)+ }+ })++ return {+ removed: removed.map((r) => ({ ...r, projectId: projects.find((p) => p.ref === r.ref)?.id })),+ added: added.map((r) => ({ ...r, projectId: projects.find((p) => p.ref === r.ref)?.id })),+ updated: updated.map((r) => ({ ...r, projectId: projects.find((p) => p.ref === r.ref)?.id })),+ }+}++// [Joshen] Essentially spit out 3 arrays+// What to (1) Remove (2) Assign (3) Update+// And so that we can unit test this+export const deriveRoleChangeActions = (+ existingRoles: OrganizationRole[],+ changesToRoles: {+ removed: ProjectRoleConfiguration[]+ added: ProjectRoleConfiguration[]+ updated: {+ ref?: string+ projectId?: number+ originalRole: number+ originalBaseRole?: number+ updatedRole: number+ }[]+ }+) => {+ const { removed, added, updated } = changesToRoles+ const toRemove: number[] = []+ const toAssign: { roleId: number; projectIds: number[] }[] = []+ const toUpdate: { roleId: number; projectIds: number[] }[] = []++ const groupByAddedRoles = groupBy(added, 'roleId')+ const groupByRemovedRoles = groupBy(removed, 'roleId')+ const groupByUpdatingFromRoles = groupBy(updated, 'originalRole')+ const groupByUpdatingToRoles = groupBy(updated, 'updatedRole')+ const existingProjectRolesByBaseIds = existingRoles+ .filter((r) => (r?.project_ids ?? []).length > 0)+ .map((r) => r.base_role_id)++ existingRoles.forEach((role) => {+ const projectIdsApplied = role.project_ids+ if (projectIdsApplied === null) {+ // [Joshen] In this case we're removing an org scope role, skip all the chekcs+ return toRemove.push(role.id)+ }+ const toRemoveRole = projectIdsApplied.every((id) => {+ const isRemoved = removed.map((r) => r.projectId).some((x) => x === id)+ const isUpdated = updated.map((r) => r.projectId).some((x) => x === id)+ return isRemoved || isUpdated+ })+ const isRoleGettingAdded = added.some((r) => r.roleId === role.base_role_id)+ const isRoleGettingUpdatedTo = updated.some((r) => r.updatedRole === role.base_role_id)++ if (toRemoveRole && !isRoleGettingAdded && !isRoleGettingUpdatedTo) {+ return toRemove.push(role.id)+ }++ const projectsToAddToRole = (groupByAddedRoles[role.base_role_id]?.map((r) => r.projectId) ??+ []) as number[]+ const projectsToRemoveFromRole = (groupByRemovedRoles[role.id]?.map((r) => r.projectId) ??+ []) as number[]+ const projectsUpdatingFromRole = (groupByUpdatingFromRoles[role.id]?.map((r) => r.projectId) ??+ []) as number[]+ const projectsUpdatingToRole = (groupByUpdatingToRoles[role.base_role_id]?.map(+ (r) => r.projectId+ ) ?? []) as number[]+ const projectIdsAppliedUpdated = projectIdsApplied+ .filter((x) => !projectsToRemoveFromRole.includes(x))+ .filter((x) => !projectsUpdatingFromRole.includes(x))+ .concat(projectsToAddToRole)+ .concat(projectsUpdatingToRole)++ if (!isEqual(projectIdsApplied, projectIdsAppliedUpdated)) {+ toUpdate.push({ roleId: role.id, projectIds: projectIdsAppliedUpdated.sort((a, b) => a - b) })+ }+ })++ Object.keys(groupByAddedRoles).forEach((roleId) => {+ if (!existingProjectRolesByBaseIds.includes(Number(roleId))) {+ toAssign.push({+ roleId: Number(roleId),+ projectIds: (groupByAddedRoles[roleId].map((x) => x.projectId) as number[]).sort(+ (a, b) => a - b+ ),+ })+ }+ })++ Object.keys(groupByUpdatingToRoles).forEach((roleId) => {+ if (!existingProjectRolesByBaseIds.includes(Number(roleId))) {+ toAssign.push({+ roleId: Number(roleId),+ projectIds: (groupByUpdatingToRoles[roleId].map((x) => x.projectId) as number[]).sort(+ (a, b) => a - b+ ),+ })+ }+ })++ // [Joshen] Am sorting the results just so its more deterministic when writing tests+ return { toRemove: toRemove.sort((a, b) => a - b), toAssign, toUpdate }+}diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanelOld.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanelOld.tsxnew file mode 100644index 00000000000..bc2ffc34065--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/UpdateRolesPanel/UpdateRolesPanelOld.tsx@@ -0,0 +1,255 @@+import { useParams } from 'common'+import { OrganizationMember } from 'data/organizations/organization-members-query'+import { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'+import { useProjectsQuery } from 'data/projects/projects-query'+import { useSelectedOrganization } from 'hooks'+import { PanelLeftClose, PanelRightClose } from 'lucide-react'+import { useEffect, useState } from 'react'+import { Role } from 'types'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+ cn,+} from 'ui'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'+import { MultiSelectV2 } from 'ui-patterns/MultiSelectDeprecated/MultiSelectV2'+import { RolesAccessMatrix } from './RolesAccessMatrix'++interface UpdateRolesPanelProps {+ visible: boolean+ member: OrganizationMember+ onClose: () => void+}++// [Joshen] This is just scaffolding the UI logic, will need to change quite a bit to fit the API structure+// [Joshen] Keeping this for now, but once everything is ready we can deprecate this file, no one is using++export const UpdateRolesPanel = ({ visible, member, onClose }: UpdateRolesPanelProps) => {+ const { slug } = useParams()+ const organization = useSelectedOrganization()+ const { data } = useOrganizationRolesQuery({ slug })+ const { data: projects } = useProjectsQuery()++ const [showRolesAccessMatrix, setShowRolesAccessMatrix] = useState(false)+ const [roleConfiguration, setRoleConfiguration] = useState<+ { id: number; name: string; projects: string[] }[]+ >([])++ // [Joshen] If any roles are applied to ALL projects, or there are overlapping projects across roles+ const hasMoreThanOneRoleForAllProjects =+ roleConfiguration.some((r) => r.projects.length === 0) && roleConfiguration.length > 1+ const selectedProjectsAcrossRoles = roleConfiguration.reduce((obj, item) => {+ return obj.concat(item.projects)+ }, [] as string[])+ const hasOverlappingProjects =+ new Set(selectedProjectsAcrossRoles).size !== selectedProjectsAcrossRoles.length+ const canSaveRoles =+ roleConfiguration.length > 0 && !hasOverlappingProjects && !hasMoreThanOneRoleForAllProjects++ const availableRoles = data?.roles ?? []+ const appliedRoles = member.role_ids+ .map((id) => {+ return availableRoles.find((y) => id === y.id)+ })+ .filter((x) => x !== undefined) as Role[]++ const sortByObject: any = ['Owner', 'Administrator', 'Developer'].reduce((obj, item, index) => {+ return { ...obj, [item]: index }+ }, {})++ const onAddRole = (role: Role) => {+ const updatedConfiguration = roleConfiguration.concat({ ...role, projects: [] })+ setRoleConfiguration(+ updatedConfiguration.sort((a, b) => sortByObject[a.name] - sortByObject[b.name])+ )+ }++ const onRemoveRole = (role: Role) => {+ setRoleConfiguration(roleConfiguration.filter((r) => r.id !== role.id))+ }++ const onUpdateRole = (role: Role, projects: string[]) => {+ const updatedConfiguration = roleConfiguration.map((r) => {+ if (role.id === r.id) {+ return { ...r, projects }+ } else {+ return r+ }+ })+ setRoleConfiguration(updatedConfiguration)+ }++ useEffect(() => {+ // [Joshen] This is an assumption for the structure+ if (visible) {+ setRoleConfiguration(+ appliedRoles.map((role) => {+ return { ...role, projects: [] }+ })+ )+ } else {+ setShowRolesAccessMatrix(false)+ }+ }, [visible])++ return (+ <Sheet open={visible} onOpenChange={() => onClose()}>+ <SheetContent+ showClose={false}+ size={showRolesAccessMatrix ? 'lg' : 'default'}+ className={cn(+ 'bg-surface-200 p-0 flex flex-row gap-0',+ showRolesAccessMatrix ? '!min-w-[1000px]' : '!min-w-[400px]'+ )}+ >+ <div className={cn('flex flex-col grow', showRolesAccessMatrix ? 'w-[48%]' : 'w-full')}>+ <SheetHeader className={cn('py-3 flex flex-row justify-between items-center border-b')}>+ <p>Manage access for team member</p>+ <Tooltip_Shadcn_ delayDuration={100}>+ <TooltipTrigger_Shadcn_ asChild>+ <button+ aria-expanded={showRolesAccessMatrix}+ aria-controls="show-roles-matrix"+ className={cn(+ !showRolesAccessMatrix ? 'text-foreground-lighter' : 'text-light',+ 'mt-1 hover:text-foreground transition'+ )}+ onClick={() => setShowRolesAccessMatrix(!showRolesAccessMatrix)}+ >+ {!showRolesAccessMatrix ? (+ <PanelLeftClose size={19} strokeWidth={1} />+ ) : (+ <PanelRightClose size={19} strokeWidth={1} />+ )}+ </button>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="left">+ {showRolesAccessMatrix ? 'Hide' : 'Show'} role permissions+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </SheetHeader>++ <div className="h-full flex flex-col gap-y-4 px-5 py-5">+ <p className="text-sm">+ Manage access for {member.username} to each project under {organization?.name}+ </p>++ {(hasOverlappingProjects || hasMoreThanOneRoleForAllProjects) && (+ <Alert_Shadcn_ variant="warning">+ <WarningIcon />+ <AlertTitle_Shadcn_>+ Members cannot be assigned multiple roles on a project+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ Ensure that the member has at most one role assigned for each project+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ {roleConfiguration.length === 0 && (+ <Alert_Shadcn_>+ <WarningIcon />+ <AlertTitle_Shadcn_>+ Team members need to be assigned at least one role+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ You may not remove all roles from a team member+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ )}++ {roleConfiguration.map((role) => {+ const selectedProjects =+ roleConfiguration.find((r) => r.id === role.id)?.projects ?? []++ return (+ <div+ key={role.name}+ className="flex flex-col border border-control rounded gap-y-2 px-3 py-3 bg-surface-200"+ >+ <div className="flex items-center justify-between">+ <p className="text-sm">{role.name}</p>+ <div className="flex items-center gap-x-2">+ {role.projects.length > 0 && (+ <Button type="default" onClick={() => onUpdateRole(role, [])}>+ Apply to all projects+ </Button>+ )}+ <Button type="default" onClick={() => onRemoveRole(role)}>+ Remove role+ </Button>+ </div>+ </div>+ <MultiSelectV2+ options={(projects ?? []).map((project) => {+ return {+ id: project.id,+ name: project.name,+ value: project.ref,+ disabled: false,+ }+ })}+ value={selectedProjects}+ placeholder="All projects"+ searchPlaceholder="Search for a project"+ onChange={(projects) => onUpdateRole(role, projects)}+ />+ </div>+ )+ })}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="default" className="w-min">+ Assign a new role+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" align="start">+ {availableRoles+ .sort((a, b) => sortByObject[a.name] - sortByObject[b.name])+ .map((role) => {+ const alreadyAssigned = roleConfiguration.map((x) => x.id).includes(role.id)+ return (+ <DropdownMenuItem+ key={role.id}+ disabled={alreadyAssigned}+ className="flex items-center justify-between"+ onClick={() => onAddRole(role)}+ >+ <span className="text-foreground">{role.name}</span>+ {alreadyAssigned && (+ <span className="text-foreground-light">Already assigned</span>+ )}+ </DropdownMenuItem>+ )+ })}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ <SheetFooter className="flex items-center !justify-end px-5 py-4 w-full border-t">+ <Button type="default" disabled={false} onClick={() => onClose()}>+ Cancel+ </Button>+ <Button loading={false} disabled={!canSaveRoles} onClick={() => {}}>+ Save roles+ </Button>+ </SheetFooter>+ </div>+ {showRolesAccessMatrix && <RolesAccessMatrix visible={showRolesAccessMatrix} />}+ </SheetContent>+ </Sheet>+ )+}diff --git a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx b/apps/studio/components/interfaces/Organization/Usage/Usage.tsxindex fb0501db851..85dcd4fce2c 100644--- a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx+++ b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx@@ -1,31 +1,39 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import clsx from 'clsx'import dayjs from 'dayjs'+import { ExternalLink } from 'lucide-react'+import Link from 'next/link'import { useEffect, useMemo, useState } from 'react'import { useParams } from 'common'-import { ScaffoldContainer } from 'components/layouts/Scaffold'+import { ScaffoldContainer, ScaffoldContainerLegacy } from 'components/layouts/Scaffold'import DateRangePicker from 'components/to-be-cleaned/DateRangePicker'import AlertError from 'components/ui/AlertError'import InformationBox from 'components/ui/InformationBox'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useProjectsQuery } from 'data/projects/projects-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'-import { useSelectedOrganization } from 'hooks'+import { useCheckPermissions, useSelectedOrganization } from 'hooks'import { TIME_PERIODS_BILLING, TIME_PERIODS_REPORTS } from 'lib/constants/metrics'-import Link from 'next/link'-import { Button, IconExternalLink, IconInfo, Listbox } from 'ui'+import { Button, IconInfo, Listbox } from 'ui'import { Restriction } from '../BillingSettings/Restriction'import Activity from './Activity'import Bandwidth from './Bandwidth'import Compute from './Compute'import SizeAndCounts from './SizeAndCounts'import TotalUsage from './TotalUsage'+import NoPermission from 'components/ui/NoPermission'const Usage = () => {const { slug, projectRef } = useParams()const [dateRange, setDateRange] = useState<any>()const [selectedProjectRef, setSelectedProjectRef] = useState<string>()+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )+const organization = useSelectedOrganization()const { data: projects, isSuccess } = useProjectsQuery()const {@@ -92,6 +100,14 @@ const Usage = () => {? orgProjects?.find((it) => it.ref === selectedProjectRef): undefined+ if (!canReadSubscriptions) {+ return (+ <ScaffoldContainerLegacy>+ <NoPermission resourceText="view organization usage" />+ </ScaffoldContainerLegacy>+ )+ }+return (<><ScaffoldContainer className="sticky top-0 border-b bg-studio z-10 overflow-hidden">@@ -176,7 +192,7 @@ const Usage = () => {"All Projects".</p><div>- <Button asChild type="default" icon={<IconExternalLink strokeWidth={1.5} />}>+ <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}><Linkhref="https://supabase.com/docs/guides/platform/org-based-billing"target="_blank"diff --git a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsx b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsxnew file mode 100644index 00000000000..c40ea9d4cd3--- /dev/null+++ b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsx@@ -0,0 +1,122 @@+import { CheckSquare } from 'lucide-react'+import Link from 'next/link'+import { useRouter } from 'next/router'+import toast from 'react-hot-toast'++import { useParams } from 'common'+import { useOrganizationAcceptInvitationMutation } from 'data/organization-members/organization-invitation-accept-mutation'+import { useOrganizationDeleteInvitationMutation } from 'data/organization-members/organization-invitation-delete-mutation'+import { useOrganizationInvitationTokenQuery } from 'data/organization-members/organization-invitation-token-query'+import { useProfile } from 'lib/profile'+import { ResponseError } from 'types'+import { Button, Loading, cn } from 'ui'+import { OrganizationInviteError } from './OrganizationInviteError'++export const OrganizationInvite = () => {+ const router = useRouter()+ const { profile } = useProfile()+ const { slug, token, name } = useParams()++ const { data, error, isSuccess, isError, isLoading } = useOrganizationInvitationTokenQuery(+ { slug, token },+ {+ retry: false,+ refetchOnWindowFocus: false,+ }+ )+ const hasError =+ isError || (isSuccess && (data.token_does_not_exist || data.expired_token || !data.email_match))++ const organizationName = data?.organization_name ?? name ?? 'an organization'+ const loginRedirectLink = `/?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`++ const { mutate: joinOrganization, isLoading: isJoining } =+ useOrganizationAcceptInvitationMutation({+ onSuccess: () => {+ router.push('/')+ },+ onError: (error) => {+ toast.error(`Failed to join organization: ${error.message}`)+ },+ })++ const { mutate: declineOrganization, isLoading: isDeclining } =+ useOrganizationDeleteInvitationMutation({+ onSuccess: () => {+ router.push('/')+ },+ onError: (error) => {+ toast.error(`Failed to decline invitation: ${error.message}`)+ },+ })++ async function handleJoinOrganization() {+ if (!slug) return console.error('Slug is required')+ if (!token) return console.error('Token is required')+ joinOrganization({ slug, token })+ }++ async function handleDeclineJoinOrganization() {+ if (!slug) return console.error('Slug is required')+ if (!data?.invite_id) return console.error('Invite ID is required')+ declineOrganization({ slug, id: data.invite_id })+ }++ return (+ <Loading active={profile !== undefined && isLoading}>+ <div className="flex flex-col gap-2 px-6 py-8">+ <p className="text-sm text-foreground">You have been invited to join </p>+ <p className="text-3xl text-foreground">{organizationName}</p>+ {slug && <p className="text-xs text-foreground-lighter">{`organization slug: ${slug}`}</p>}+ </div>++ <div className={cn('border-t border-muted', hasError ? 'bg-alternative' : 'bg-transparent')}>+ <div className={cn('flex flex-col gap-4', !isLoading && !hasError && 'px-6 py-4')}>+ {profile === undefined && (+ <div className="flex flex-col gap-3">+ <p className="text-xs text-foreground-lighter">+ You will need to sign in to accept this invitation+ </p>+ <div className="flex justify-center gap-3">+ <Button asChild type="default">+ <Link href={loginRedirectLink}>Sign in</Link>+ </Button>+ <Button asChild type="default">+ <Link href={loginRedirectLink}>Create an account</Link>+ </Button>+ </div>+ </div>+ )}+ {hasError && (+ <OrganizationInviteError+ data={data}+ error={error as unknown as ResponseError}+ isError={isError}+ />+ )}+ {isSuccess && (+ <div className="flex flex-row items-center justify-center gap-3">+ <Button+ type="default"+ loading={isDeclining}+ disabled={isJoining || isDeclining}+ onClick={handleDeclineJoinOrganization}+ >+ Decline+ </Button>+ <Button+ type="primary"+ loading={isJoining}+ disabled={isJoining || isDeclining}+ onClick={handleJoinOrganization}+ icon={<CheckSquare />}+ >+ Join organization+ </Button>+ </div>+ )}+ </div>+ </div>+ </Loading>+ )+}diff --git a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsx b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsxnew file mode 100644index 00000000000..59c30621bea--- /dev/null+++ b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsx@@ -0,0 +1,76 @@+import { useRouter } from 'next/router'++import AlertError from 'components/ui/AlertError'+import { OrganizationInviteByToken } from 'data/organization-members/organization-invitation-token-query'+import { useSignOut } from 'lib/auth'+import { useProfile } from 'lib/profile'+import { ResponseError } from 'types'+import { cn } from 'ui'++interface OrganizationInviteError {+ data?: OrganizationInviteByToken+ error?: ResponseError+ isError: boolean+}++export const OrganizationInviteError = ({ data, error, isError }: OrganizationInviteError) => {+ const router = useRouter()+ const signOut = useSignOut()+ const { profile } = useProfile()++ const hasError =+ isError || data?.token_does_not_exist || data?.expired_token || !data?.email_match++ return (+ <div+ className={cn(+ 'flex flex-col items-center justify-center gap-y-1 text-sm',+ hasError ? 'text-foreground-light' : 'text-foreground'+ )}+ >+ {isError ? (+ <AlertError+ error={error}+ subject="Failed to retrieve token"+ className="[&>h5]:text-left [&>div]:items-start rounded-t-none"+ />+ ) : data?.token_does_not_exist ? (+ <>+ <p>The invite token is invalid.</p>+ <p className="text-foreground-lighter">+ Try copying and pasting the link from the invite email, or ask the organization owner to+ invite you again.+ </p>+ </>+ ) : !data?.email_match ? (+ <>+ <p>+ Your email address {profile?.primary_email} does not match the email address this+ invitation was sent to.+ </p>+ <p className="text-foreground-lighter">+ To accept this invitation, you will need to{' '}+ <a+ className="cursor-pointer text-brand"+ onClick={async () => {+ await signOut()+ router.reload()+ }}+ >+ sign out+ </a>{' '}+ and then sign in or create a new account using the same email address used in the+ invitation.+ </p>+ </>+ ) : data.expired_token ? (+ <>+ <p>The invite token has expired.</p>+ <p className="text-foreground-lighter">+ Please request a new one from the organization owner.+ </p>+ </>+ ) : null}+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Reports/GridResize.tsx b/apps/studio/components/interfaces/Reports/GridResize.tsxindex 3c7af8abd36..8f5251bfda1 100644--- a/apps/studio/components/interfaces/Reports/GridResize.tsx+++ b/apps/studio/components/interfaces/Reports/GridResize.tsx@@ -6,6 +6,8 @@ import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { Button, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_ } from 'ui'import { LAYOUT_COLUMN_COUNT } from './Reports.constants'+import { useCheckPermissions } from 'hooks'+import { PermissionAction } from '@supabase/shared-types/out/constants'const ReactGridLayout = WidthProvider(RGL)@@ -14,6 +16,7 @@ interface GridResizeProps {endDate: stringinterval: stringeditableReport: any+ disableUpdate: booleanonRemoveChart: ({ metric }: { metric: { key: string } }) => voidsetEditableReport: (payload: any) => void}@@ -23,6 +26,7 @@ const GridResize = ({endDate,interval,editableReport,+ disableUpdate,onRemoveChart,setEditableReport,}: GridResizeProps) => {@@ -74,17 +78,19 @@ const GridResize = ({label={`${x.label}${ref !== state.selectedDatabaseId ? (x.provider === 'infra-monitoring' ? ' of replica' : ' on project') : ''}`}customDateFormat={'MMM D, YYYY'}>- <Tooltip_Shadcn_>- <TooltipTrigger_Shadcn_ asChild>- <Button- type="text"- icon={<X />}- className="ml-2 px-1"- onClick={() => onRemoveChart({ metric: { key: x.attribute } })}- />- </TooltipTrigger_Shadcn_>- <TooltipContent_Shadcn_ side="bottom">Remove chart</TooltipContent_Shadcn_>- </Tooltip_Shadcn_>+ {!disableUpdate && (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ type="text"+ icon={<X />}+ className="ml-2 px-1"+ onClick={() => onRemoveChart({ metric: { key: x.attribute } })}+ />+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">Remove chart</TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ )}</ChartHandler><div className="absolute inset-x-0 top-3 ">diff --git a/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsx b/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsxindex ccb2193ee67..69320de83e8 100644--- a/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsx+++ b/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsx@@ -1,7 +1,8 @@+import toast from 'react-hot-toast'+import { useParams } from 'common'import { Content } from 'data/content/content-query'import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'-import toast from 'react-hot-toast'import { Button, Form, Input, Modal } from 'ui'type CustomReport = { name: string; description?: string }@@ -18,7 +19,7 @@ export const UpdateCustomReportModal = ({onCancel,}: UpdateCustomReportProps) => {const { ref } = useParams()- const { mutate: updateReport } = useContentUpsertMutation({+ const { mutate: updateReport, isLoading: isUpdating } = useContentUpsertMutation({onSuccess: () => {toast.success('Successfully updated report')onCancel()@@ -67,7 +68,7 @@ export const UpdateCustomReportModal = ({validate={validate}onSubmit={onConfirmUpdateReport}>- {({ isSubmitting }: { isSubmitting: boolean }) => (+ {() => (<><Modal.Content><Input label="Name" id="name" name="name" />@@ -83,10 +84,10 @@ export const UpdateCustomReportModal = ({</Modal.Content><Modal.Separator /><Modal.Content className="flex items-center justify-end gap-2">- <Button htmlType="reset" type="default" onClick={onCancel} disabled={isSubmitting}>+ <Button htmlType="reset" type="default" onClick={onCancel} disabled={isUpdating}>Cancel</Button>- <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting}>+ <Button htmlType="submit" loading={isUpdating} disabled={isUpdating}>Save custom report</Button></Modal.Content>diff --git a/apps/studio/components/interfaces/Reports/Reports.tsx b/apps/studio/components/interfaces/Reports/Reports.tsxindex 63c225deaad..df195136b5d 100644--- a/apps/studio/components/interfaces/Reports/Reports.tsx+++ b/apps/studio/components/interfaces/Reports/Reports.tsx@@ -5,7 +5,6 @@ import { useEffect, useState } from 'react'import toast from 'react-hot-toast'import { useParams } from 'common'-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import DateRangePicker from 'components/to-be-cleaned/DateRangePicker'import DatabaseSelector from 'components/ui/DatabaseSelector'import { Loading } from 'components/ui/Loading'@@ -29,6 +28,7 @@ import {import GridResize from './GridResize'import { MetricOptions } from './MetricOptions'import { LAYOUT_COLUMN_COUNT } from './Reports.constants'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'const DEFAULT_CHART_COLUMN_COUNT = 12const DEFAULT_CHART_ROW_COUNT = 4@@ -36,7 +36,6 @@ const DEFAULT_CHART_ROW_COUNT = 4const Reports = () => {const { id, ref } = useParams()const { profile } = useProfile()- const { project } = useProjectContext()const [config, setConfig] = useState<any>(undefined)const [startDate, setStartDate] = useState<any>(null)@@ -205,7 +204,7 @@ const Reports = () => {}if (!canReadReport) {- return <NoPermission isFullPage resourceText="access this project's report" />+ return <NoPermission isFullPage resourceText="access this custom report" />}return (@@ -272,16 +271,20 @@ const Reports = () => {</DropdownMenuContent></DropdownMenu>) : (- <Tooltip_Shadcn_>- <TooltipTrigger_Shadcn_ asChild>- <Button disabled type="default" iconRight={<Settings size={14} />}>- Add / Remove charts- </Button>- </TooltipTrigger_Shadcn_>- <TooltipContent_Shadcn_ side="bottom" className="w-56 text-center" align="end">- You need additional permissions to update this project's report- </TooltipContent_Shadcn_>- </Tooltip_Shadcn_>+ <ButtonTooltip+ disabled+ type="default"+ iconRight={<Settings size={14} />}+ tooltip={{+ content: {+ side: 'bottom',+ className: 'w-56 text-center',+ text: 'You need additional permissions to update custom reports',+ },+ }}+ >+ Add / Remove charts+ </ButtonTooltip>)}<DatabaseSelector /></div>@@ -314,6 +317,7 @@ const Reports = () => {endDate={endDate}interval={config.interval}editableReport={config}+ disableUpdate={!canUpdateReport}onRemoveChart={popChart}setEditableReport={setConfig}/>diff --git a/apps/studio/components/interfaces/Settings/API/JWTSettings.tsx b/apps/studio/components/interfaces/Settings/API/JWTSettings.tsxindex 8dd279f79ce..e169d882d6d 100644--- a/apps/studio/components/interfaces/Settings/API/JWTSettings.tsx+++ b/apps/studio/components/interfaces/Settings/API/JWTSettings.tsx@@ -1,14 +1,24 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import {JwtSecretUpdateError,JwtSecretUpdateProgress,JwtSecretUpdateStatus,} from '@supabase/shared-types/out/events'+import {+ AlertCircle,+ ChevronDown,+ Eye,+ EyeOff,+ Key,+ Loader2,+ PenTool,+ RefreshCw,+} from 'lucide-react'import { Dispatch, SetStateAction, useState } from 'react'import toast from 'react-hot-toast'import { useParams } from 'common'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import Panel from 'components/ui/Panel'import { useJwtSecretUpdateMutation } from 'data/config/jwt-secret-update-mutation'import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating-status-query'@@ -26,19 +36,11 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,- IconAlertCircle,- IconAlertTriangle,- IconChevronDown,- IconEye,- IconEyeOff,- IconKey,- IconLoader,- IconPenTool,- IconRefreshCw,Input,Modal,} from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'import {JWT_SECRET_UPDATE_ERROR_MESSAGES,JWT_SECRET_UPDATE_PROGRESS_MESSAGES,@@ -95,7 +97,7 @@ const JWTSettings = () => {<Panel.Content className="space-y-6 border-t border-panel-border-interior-light [[data-theme*=dark]_&]:border-panel-border-interior-dark">{isError ? (<div className="flex items-center justify-center py-8 space-x-2">- <IconAlertCircle size={16} strokeWidth={1.5} />+ <AlertCircle size={16} strokeWidth={1.5} /><p className="text-sm text-foreground-light">Failed to retrieve JWT settings</p></div>) : (@@ -125,7 +127,7 @@ const JWTSettings = () => {<div className="p-3 px-6 border rounded-md shadow-sm bg-studio">{isUpdatingJwtSecret ? (<div className="flex items-center space-x-2">- <IconLoader className="animate-spin" size={14} />+ <Loader2 className="animate-spin" size={14} /><p className="text-sm">Updating JWT secret: {jwtSecretUpdateProgressMessage}</p>@@ -145,32 +147,23 @@ const JWTSettings = () => {Updating JWT secret...</Button>) : !canGenerateNewJWTSecret ? (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button disabled type="default" iconRight={<IconChevronDown />}>- Generate a new secret- </Button>- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to generate a new JWT secret- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>+ <ButtonTooltip+ disabled+ type="default"+ iconRight={<ChevronDown size={14} />}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to generate a new JWT secret',+ },+ }}+ >+ Generate a new secret+ </ButtonTooltip>) : (<DropdownMenu><DropdownMenuTrigger asChild>- <Button type="default" iconRight={<IconChevronDown />}>+ <Button type="default" iconRight={<ChevronDown size={14} />}><span>Generate a new secret</span></Button></DropdownMenuTrigger>@@ -179,7 +172,7 @@ const JWTSettings = () => {className="space-x-2"onClick={() => setIsGeneratingKey(true)}>- <IconRefreshCw size={16} />+ <RefreshCw size={16} /><p>Generate a random secret</p></DropdownMenuItem><DropdownMenuSeparator />@@ -187,7 +180,7 @@ const JWTSettings = () => {className="space-x-2"onClick={() => setIsCreatingKey(true)}>- <IconPenTool size={16} />+ <PenTool size={16} /><p>Create my own secret</p></DropdownMenuItem></DropdownMenuContent>@@ -241,7 +234,6 @@ const JWTSettings = () => {</ConfirmationModal><Modal- closableheader="Create a custom JWT secret"visible={isCreatingKey}size="medium"@@ -271,7 +263,7 @@ const JWTSettings = () => {cannot be guessed easily.</p><Alert_Shadcn_ variant="warning">- <IconAlertTriangle />+ <WarningIcon /><AlertTitle_Shadcn_>This will invalidate all existing API keys</AlertTitle_Shadcn_><AlertDescription_Shadcn_>Generating a new JWT secret will invalidate <u className="text-foreground">all</u> of@@ -283,7 +275,7 @@ const JWTSettings = () => {<InputonChange={(e: any) => setCustomToken(e.target.value)}value={customToken}- icon={<IconKey />}+ icon={<Key />}type={showCustomTokenInput ? 'text' : 'password'}className="w-full text-left"label="Custom JWT secret"@@ -292,7 +284,7 @@ const JWTSettings = () => {<div className="flex items-center justify-center mr-1"><Buttontype="default"- icon={showCustomTokenInput ? <IconEye /> : <IconEyeOff />}+ icon={showCustomTokenInput ? <Eye /> : <EyeOff />}onClick={() => setShowCustomTokenInput(!showCustomTokenInput)}/></div>diff --git a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsxindex 171494f2053..505eb84a951 100644--- a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx+++ b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx@@ -101,6 +101,7 @@ const PostgrestConfig = () => {PermissionAction.UPDATE,'custom_config_postgrest')+const isGraphqlExtensionEnabled =(extensions ?? []).find((ext) => ext.name === 'pg_graphql')?.installed_version !== null@@ -207,6 +208,7 @@ const PostgrestConfig = () => {<FormControl_Shadcn_><Switchsize="large"+ disabled={!canUpdatePostgrestConfig}checked={field.value}onCheckedChange={(value) => {field.onChange(value)diff --git a/apps/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx b/apps/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsxindex b6619f8804d..607a29210b7 100644--- a/apps/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx+++ b/apps/studio/components/interfaces/Settings/Addons/ComputeInstanceSidePanel.tsx@@ -34,7 +34,7 @@ import {Radio,SidePanel,} from 'ui'-import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'+import { CriticalIcon, WarningIcon } from 'ui-patterns/Icons/StatusIcons'const ComputeInstanceSidePanel = () => {const queryClient = useQueryClient()@@ -449,7 +449,7 @@ const ComputeInstanceSidePanel = () => {subscription?.billing_via_partner &&subscription.scheduled_plan_change?.target_plan !== undefined && (<Alert_Shadcn_ variant={'warning'} className="mb-2">- <IconAlertTriangle className="h-4 w-4" />+ <CriticalIcon /><AlertDescription_Shadcn_>You have a scheduled subscription change that will be canceled if you changeyour compute size.diff --git a/apps/studio/components/interfaces/Settings/Database/BannedIPs.tsx b/apps/studio/components/interfaces/Settings/Database/BannedIPs.tsxindex 6b3ec7a5302..d289ca25546 100644--- a/apps/studio/components/interfaces/Settings/Database/BannedIPs.tsx+++ b/apps/studio/components/interfaces/Settings/Database/BannedIPs.tsx@@ -1,27 +1,22 @@-import Link from 'next/link'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { ExternalLink, Globe } from 'lucide-react'import { useEffect, useState } from 'react'import toast from 'react-hot-toast'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { useParams } from 'common'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { FormHeader, FormPanel } from 'components/ui/Forms'import { useBannedIPsDeleteMutation } from 'data/banned-ips/banned-ips-delete-mutations'import { useBannedIPsQuery } from 'data/banned-ips/banned-ips-query'+import { useCheckPermissions } from 'hooks'import { BASE_PATH } from 'lib/constants'-import {- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,- Badge,- Button,- IconAlertTriangle,- IconExternalLink,- IconGlobe,- Modal,-} from 'ui'+import { Badge, Button } from 'ui'const BannedIPs = () => {const { ref } = useParams()+ const { project } = useProjectContext()const [selectedIPToUnban, setSelectedIPToUnban] = useState<string | null>(null) // Track the selected IP for unbanconst { data: ipList } = useBannedIPsQuery({projectRef: ref,@@ -30,6 +25,12 @@ const BannedIPs = () => {const [showUnban, setShowUnban] = useState(false)const [confirmingIP, setConfirmingIP] = useState<string | null>(null) // Track the IP being confirmed for unban+ const canUnbanNetworks = useCheckPermissions(PermissionAction.UPDATE, 'projects', {+ resource: {+ project_id: project?.id,+ },+ })+const { mutate: unbanIPs, isLoading: isUnbanning } = useBannedIPsDeleteMutation({onSuccess: () => {toast.success('IP address successfully unbanned')@@ -57,6 +58,7 @@ const BannedIPs = () => {const [userIPAddress, setUserIPAddress] = useState<string | null>(null)+ // [TODO] Convert this to a react queryuseEffect(() => {// Fetch user's IP addressfetch(`${BASE_PATH}/api/get-ip-address`)@@ -72,13 +74,10 @@ const BannedIPs = () => {description="List of IP addresses that are temporarily blocked if their traffic pattern looks abusive"/><div className="flex items-center space-x-2 mb-6">- <Button asChild type="default" icon={<IconExternalLink />}>- <Link- href="https://supabase.com/docs/reference/cli/supabase-network-bans"- target="_blank"- >+ <Button asChild type="default" icon={<ExternalLink />}>+ <a target="_blank" href="https://supabase.com/docs/reference/cli/supabase-network-bans">Documentation- </Link>+ </a></Button></div></div>@@ -87,14 +86,24 @@ const BannedIPs = () => {ipList.banned_ipv4_addresses.map((ip) => (<div key={ip} className="px-8 py-4 flex items-center justify-between"><div className="flex items-center space-x-5">- <IconGlobe size={16} className="text-foreground-lighter" />+ <Globe size={16} className="text-foreground-lighter" /><p className="text-sm font-mono">{ip}</p>{ip === userIPAddress && <Badge>Your IP address</Badge>}</div><div>- <Button type="default" onClick={() => openConfirmationModal(ip)}>+ <ButtonTooltip+ type="default"+ disabled={!canUnbanNetworks}+ onClick={() => openConfirmationModal(ip)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to unban networks',+ },+ }}+ >Unban IP- </Button>+ </ButtonTooltip></div></div>))diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsxindex 0407bb9eefe..1df9a5ceaf4 100644--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx@@ -1,11 +1,17 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import generator from 'generate-password-browser'import { debounce } from 'lodash'import { useEffect, useRef, useState } from 'react'import toast from 'react-hot-toast'-import { Button, Input, Modal } from 'ui'+import {+ Button,+ Input,+ Modal,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+} from 'ui'import {useIsProjectActive,@@ -17,6 +23,7 @@ import { useDatabasePasswordResetMutation } from 'data/database/database-passworimport { useCheckPermissions } from 'hooks'import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from 'lib/constants'import { passwordStrength } from 'lib/helpers'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'const ResetDbPassword = ({ disabled = false }) => {const { ref } = useParams()@@ -105,38 +112,23 @@ const ResetDbPassword = ({ disabled = false }) => {</p></div><div className="flex items-end justify-end">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="default"- disabled={!canResetDbPassword || !isProjectActive || disabled}- onClick={() => setShowResetDbPass(true)}- >- Reset database password- </Button>- </Tooltip.Trigger>- {(!canResetDbPassword || !isProjectActive) && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- {!canResetDbPassword- ? 'You need additional permissions to reset the database password'- : !isProjectActive- ? 'Unable to reset database password as project is not active'- : ''}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ type="default"+ disabled={!canResetDbPassword || !isProjectActive || disabled}+ onClick={() => setShowResetDbPass(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canResetDbPassword+ ? 'You need additional permissions to reset the database password'+ : !isProjectActive+ ? 'Unable to reset database password as project is not active'+ : undefined,+ },+ }}+ >+ Reset database password+ </ButtonTooltip></div></div></Panel.Content>diff --git a/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsxindex 16b3c82de11..5a6cf5101ba 100644--- a/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx@@ -1,4 +1,3 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/constants'import dayjs from 'dayjs'import { Info } from 'lucide-react'@@ -10,6 +9,7 @@ import { number, object } from 'yup'import { useParams } from 'common'import { Markdown } from 'components/interfaces/Markdown'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { FormHeader } from 'components/ui/Forms'import Panel from 'components/ui/Panel'import { useProjectDiskResizeMutation } from 'data/config/project-disk-resize-mutation'@@ -109,34 +109,21 @@ const DiskSizeConfiguration = ({ disabled = false }: DiskSizeConfigurationProps)</p></div><div className="flex items-end justify-end">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="default"- disabled={!canUpdateDiskSizeConfig || disabled}- onClick={() => setShowResetDbPass(true)}- >- Increase disk size- </Button>- </Tooltip.Trigger>- {!canUpdateDiskSizeConfig && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to increase the disk size- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ type="default"+ disabled={!canUpdateDiskSizeConfig || disabled}+ onClick={() => setShowResetDbPass(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canUpdateDiskSizeConfig+ ? 'You need additional permissions to increase the disk size'+ : undefined,+ },+ }}+ >+ Increase disk size+ </ButtonTooltip></div></div></Panel.Content>diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsxindex 86b4248febb..4b064338be4 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx@@ -1,8 +1,15 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useParams } from 'common'-import Link from 'next/link'+import { AlertCircle, ChevronDown, ExternalLink, Globe, Lock } from 'lucide-react'import { useState } from 'react'++import { useParams } from 'common'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { FormHeader, FormPanel } from 'components/ui/Forms'+import Panel from 'components/ui/Panel'+import ShimmeringLoader from 'components/ui/ShimmeringLoader'+import { useNetworkRestrictionsQuery } from 'data/network-restrictions/network-restrictions-query'+import { useCheckPermissions } from 'hooks'import {Badge,Button,@@ -10,19 +17,10 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,- IconAlertCircle,- IconChevronDown,- IconExternalLink,- IconGlobe,- IconLock,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'--import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'-import { FormHeader, FormPanel } from 'components/ui/Forms'-import Panel from 'components/ui/Panel'-import ShimmeringLoader from 'components/ui/ShimmeringLoader'-import { useNetworkRestrictionsQuery } from 'data/network-restrictions/network-restrictions-query'-import { useCheckPermissions } from 'hooks'import AddRestrictionModal from './AddRestrictionModal'import AllowAllModal from './AllowAllModal'import DisallowAllModal from './DisallowAllModal'@@ -34,57 +32,34 @@ interface AccessButtonProps {}const AllowAllAccessButton = ({ disabled, onClick }: AccessButtonProps) => (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild><Button type="default" disabled={disabled} onClick={() => onClick(true)}>Allow all access</Button>- </Tooltip.Trigger>+ </TooltipTrigger_Shadcn_>{disabled && (- <Tooltip.Portal>- <Tooltip.Content align="center" side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background w-[250px]',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to update network restrictions- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="bottom">+ You need additional permissions to update network restrictions+ </TooltipContent_Shadcn_>)}- </Tooltip.Root>+ </Tooltip_Shadcn_>)const DisallowAllAccessButton = ({ disabled, onClick }: AccessButtonProps) => (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button type="default" disabled={disabled} onClick={() => onClick(true)}>- Restrict all access- </Button>- </Tooltip.Trigger>- {disabled && (- <Tooltip.Portal>- <Tooltip.Content align="center" side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background w-[250px]',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to update network restrictions- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ disabled={disabled}+ type="default"+ onClick={() => onClick(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to update network restrictions',+ },+ }}+ >+ Restrict all access+ </ButtonTooltip>)const NetworkRestrictions = () => {@@ -114,7 +89,7 @@ const NetworkRestrictions = () => {const isAllowedAll = restrictedIps.includes('0.0.0.0/0') && restrictedIps.includes('::/0')const isDisallowedAll = restrictedIps.length === 0- if (!hasAccessToRestrictions) return <></>+ if (!hasAccessToRestrictions) return nullreturn (<>@@ -125,63 +100,57 @@ const NetworkRestrictions = () => {description="Allow specific IP ranges to have access to your database."/><div className="flex items-center space-x-2 mb-6">- <Button asChild type="default" icon={<IconExternalLink />}>- <Link+ <Button asChild type="default" icon={<ExternalLink />}>+ <ahref="https://supabase.com/docs/guides/platform/network-restrictions"target="_blank"rel="noreferrer">Documentation- </Link>+ </a></Button>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- type="primary"- disabled={!canUpdateNetworkRestrictions}- iconRight={<IconChevronDown />}- >- Add restriction- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" side="bottom" className="w-48">- <DropdownMenuItem- key="IPv4"- disabled={isLoading}- onClick={() => setIsAddingAddress('IPv4')}- >- <p className="block text-foreground">Add IPv4 restriction</p>- </DropdownMenuItem>- <DropdownMenuItem- key="IPv6"- disabled={isLoading}- onClick={() => setIsAddingAddress('IPv6')}- >- <p className="block text-foreground">Add IPv6 restriction</p>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </Tooltip.Trigger>- {!canUpdateNetworkRestrictions && (- <Tooltip.Portal>- <Tooltip.Content align="center" side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background w-[250px]',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to update network restrictions- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ {!canUpdateNetworkRestrictions ? (+ <ButtonTooltip+ disabled+ type="primary"+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to update network restrictions',+ },+ }}+ >+ Add restriction+ </ButtonTooltip>+ ) : (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="primary"+ disabled={!canUpdateNetworkRestrictions}+ iconRight={<ChevronDown size={14} />}+ >+ Add restriction+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" side="bottom" className="w-48">+ <DropdownMenuItem+ key="IPv4"+ disabled={isLoading}+ onClick={() => setIsAddingAddress('IPv4')}+ >+ <p className="block text-foreground">Add IPv4 restriction</p>+ </DropdownMenuItem>+ <DropdownMenuItem+ key="IPv6"+ disabled={isLoading}+ onClick={() => setIsAddingAddress('IPv6')}+ >+ <p className="block text-foreground">Add IPv6 restriction</p>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div></div>{isLoading ? (@@ -200,7 +169,7 @@ const NetworkRestrictions = () => {<div className="flex items-center justify-between"><div className="space-y-2"><div className="flex items-center space-x-2">- <IconAlertCircle strokeWidth={1.5} className="text-foreground-light" />+ <AlertCircle size={20} strokeWidth={1.5} className="text-foreground-light" /><p className="text-sm">Your network restrictions were not applied correctly</p></div><p className="text-sm text-foreground-light">@@ -245,7 +214,7 @@ const NetworkRestrictions = () => {) : isDisallowedAll ? (<div className="px-8 py-8 flex items-center justify-between"><div className="flex items-start space-x-4">- <IconLock className="text-foreground-light" strokeWidth={1.5} />+ <Lock size={20} className="text-foreground-light" strokeWidth={1.5} /><div className="space-y-1"><p className="text-foreground-light text-sm">Your database <span className="text-amber-900 opacity-80">cannot</span> be@@ -297,7 +266,7 @@ const NetworkRestrictions = () => {return (<div key={ip} className="px-8 py-4 flex items-center justify-between"><div className="flex items-center space-x-5">- <IconGlobe size={16} className="text-foreground-light" />+ <Globe size={16} className="text-foreground-light" /><Badge>{ipv4Restrictions.includes(ip) ? 'IPv4' : 'IPv6'}</Badge><p className="text-sm font-mono">{ip}</p></div>diff --git a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsxindex 6cc8968c6dc..1cb8ec317f5 100644--- a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx+++ b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx@@ -1,11 +1,12 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Download, ExternalLink, Loader2 } from 'lucide-react'import Link from 'next/link'import { useEffect, useState } from 'react'import toast from 'react-hot-toast'import { useParams } from 'common'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import {FormHeader,FormPanel,@@ -17,7 +18,14 @@ import { useProjectSettingsQuery } from 'data/config/project-settings-query'import { useSSLEnforcementQuery } from 'data/ssl-enforcement/ssl-enforcement-query'import { useSSLEnforcementUpdateMutation } from 'data/ssl-enforcement/ssl-enforcement-update-mutation'import { useCheckPermissions } from 'hooks'-import { Alert, Button, IconDownload, IconExternalLink, IconLoader, Toggle } from 'ui'+import {+ Alert,+ Button,+ Switch,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+} from 'ui'const SSLConfiguration = () => {const { ref } = useParams()@@ -77,7 +85,7 @@ const SSLConfiguration = () => {<div className="flex items-center justify-between"><FormHeader title="SSL Configuration" description="" /><div className="flex items-center space-x-2 mb-6">- <Button asChild type="default" icon={<IconExternalLink />}>+ <Button asChild type="default" icon={<ExternalLink />}><Link href="https://supabase.com/docs/guides/platform/ssl-enforcement" target="_blank">Documentation</Link>@@ -122,12 +130,13 @@ const SSLConfiguration = () => {<FormSectionContent loading={false} className="lg:!col-span-5"><div className="flex items-center justify-end mt-2.5 space-x-2">{(isLoading || isSubmitting) && (- <IconLoader className="animate-spin" strokeWidth={1.5} size={16} />+ <Loader2 className="animate-spin" strokeWidth={1.5} size={16} />)}{isSuccess && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger>- <Toggle+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Switch+ size="large"checked={isEnforced}disabled={isLoading ||@@ -135,31 +144,19 @@ const SSLConfiguration = () => {!canUpdateSSLEnforcement ||!hasAccessToSSLEnforcement}- onChange={toggleSSLEnforcement}+ onCheckedChange={toggleSSLEnforcement}/>- </Tooltip.Trigger>+ </TooltipTrigger_Shadcn_>{(!canUpdateSSLEnforcement || !hasAccessToSSLEnforcement) && (- <Tooltip.Portal>- <Tooltip.Content align="center" side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background w-[250px]',- ].join(' ')}- >- <span className="text-xs text-foreground text-center flex items-center justify-center">- {!canUpdateSSLEnforcement- ? 'You need additional permissions to update SSL enforcement for your project'- : !hasAccessToSSLEnforcement- ? 'Your project does not have access to SSL enforcement'- : ''}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="bottom" className="w-64 text-center">+ {!canUpdateSSLEnforcement+ ? 'You need additional permissions to update SSL enforcement for your project'+ : !hasAccessToSSLEnforcement+ ? 'Your project does not have access to SSL enforcement'+ : ''}+ </TooltipContent_Shadcn_>)}- </Tooltip.Root>+ </Tooltip_Shadcn_>)}</div></FormSectionContent>@@ -176,35 +173,29 @@ const SSLConfiguration = () => {</div></div><div className="flex items-end justify-end">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button type="default" disabled={!hasSSLCertificate} icon={<IconDownload />}>- <a- href={`https://supabase-downloads.s3-ap-southeast-1.amazonaws.com/${env}/ssl/${env}-ca-2021.crt`}- >- Download Certificate- </a>- </Button>- </Tooltip.Trigger>- {!hasSSLCertificate && (- <Tooltip.Portal>- <Tooltip.Content align="center" side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background w-[250px]',- ].join(' ')}- >- <span className="text-xs text-foreground">- Projects before 15:08 (GMT+08), 29th April 2021 do not have SSL certificates- installed- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ {!hasSSLCertificate ? (+ <ButtonTooltip+ disabled+ type="default"+ icon={<Download />}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'Projects before 15:08 (GMT+08), 29th April 2021 do not have SSL certificates installed',+ },+ }}+ >+ Download certificate+ </ButtonTooltip>+ ) : (+ <Button type="default" icon={<Download />}>+ <a+ href={`https://supabase-downloads.s3-ap-southeast-1.amazonaws.com/${env}/ssl/${env}-ca-2021.crt`}+ >+ Download certificate+ </a>+ </Button>+ )}</div></div></FormPanel>diff --git a/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.tsx b/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.tsxindex 53bc74a3069..531a5459c13 100644--- a/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.tsx+++ b/apps/studio/components/interfaces/Settings/General/Infrastructure/PauseProjectButton.tsx@@ -1,6 +1,6 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQueryClient } from '@tanstack/react-query'+import { Pause } from 'lucide-react'import { useRouter } from 'next/router'import { useState } from 'react'import toast from 'react-hot-toast'@@ -9,12 +9,12 @@ import {useIsProjectActive,useProjectContext,} from 'components/layouts/ProjectLayout/ProjectContext'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useProjectPauseMutation } from 'data/projects/project-pause-mutation'import { setProjectStatus } from 'data/projects/projects-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import { useCheckPermissions, useSelectedOrganization } from 'hooks'import { PROJECT_STATUS } from 'lib/constants'-import { Button, IconPause, Modal } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'const PauseProjectButton = () => {@@ -55,44 +55,30 @@ const PauseProjectButton = () => {return (<>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="default"- icon={<IconPause />}- onClick={() => setIsModalOpen(true)}- loading={isPausing}- disabled={buttonDisabled}- >- Pause Project- </Button>- </Tooltip.Trigger>- {buttonDisabled ? (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- {isPaused- ? 'Your project is already paused'- : !canPauseProject- ? 'You need additional permissions to pause this project'- : !isProjectActive- ? 'Unable to pause project as project is not active'- : !isFreePlan- ? 'Projects on a paid plan will always be running'- : ''}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ) : null}- </Tooltip.Root>+ <ButtonTooltip+ type="default"+ icon={<Pause />}+ onClick={() => setIsModalOpen(true)}+ loading={isPausing}+ disabled={buttonDisabled}+ tooltip={{+ content: {+ side: 'bottom',+ text: isPaused+ ? 'Your project is already paused'+ : !canPauseProject+ ? 'You need additional permissions to pause this project'+ : !isProjectActive+ ? 'Unable to pause project as project is not active'+ : !isFreePlan+ ? 'Projects on a paid plan will always be running'+ : undefined,+ },+ }}+ >+ Pause project+ </ButtonTooltip>+<ConfirmationModalvariant={'destructive'}visible={isModalOpen}diff --git a/apps/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx b/apps/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsxindex 5cb8ad5ea72..3c1afc80e7f 100644--- a/apps/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx+++ b/apps/studio/components/interfaces/Settings/General/Infrastructure/ProjectUpgradeAlert/ProjectUpgradeAlert.tsx@@ -1,4 +1,5 @@import { useQueryClient } from '@tanstack/react-query'+import { AlertCircle, AlertTriangle } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'@@ -16,8 +17,6 @@ import {Alert_Shadcn_,Button,Form,- IconAlertCircle,- IconAlertTriangle,Listbox,Modal,TooltipContent_Shadcn_,@@ -106,7 +105,7 @@ const ProjectUpgradeAlert = () => {You will not be able to downgrade back to Postgres {currentPgVersion}.</p><Alert_Shadcn_ title="Your project will be offline while the upgrade is in progress">- <IconAlertCircle className="h-4 w-4" strokeWidth={2} />+ <AlertCircle className="h-4 w-4" strokeWidth={2} /><AlertTitle_Shadcn_>Your project will be offline for up to {durationEstimateHours} hour{durationEstimateHours === 1 ? '' : 's'}@@ -120,7 +119,7 @@ const ProjectUpgradeAlert = () => {</Alert_Shadcn_>{(data?.potential_breaking_changes ?? []).length > 0 && (<Alert_Shadcn_ variant="destructive" title="Breaking changes">- <IconAlertCircle className="h-4 w-4" strokeWidth={2} />+ <AlertCircle className="h-4 w-4" strokeWidth={2} /><AlertTitle_Shadcn_>Breaking changes</AlertTitle_Shadcn_><AlertDescription_Shadcn_ className="flex flex-col gap-3"><p>@@ -147,7 +146,7 @@ const ProjectUpgradeAlert = () => {variant="warning"title="Custom Postgres roles using md5 authentication have been detected">- <IconAlertTriangle className="h-4 w-4" strokeWidth={2} />+ <AlertTriangle className="h-4 w-4" strokeWidth={2} /><AlertTitle_Shadcn_>Custom Postgres roles will not work automatically after upgrade</AlertTitle_Shadcn_>diff --git a/apps/studio/components/interfaces/Settings/General/Infrastructure/RestartServerButton.tsx b/apps/studio/components/interfaces/Settings/General/Infrastructure/RestartServerButton.tsxindex 2f9a4b10c99..c10810cdd7c 100644--- a/apps/studio/components/interfaces/Settings/General/Infrastructure/RestartServerButton.tsx+++ b/apps/studio/components/interfaces/Settings/General/Infrastructure/RestartServerButton.tsx@@ -1,4 +1,3 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQueryClient } from '@tanstack/react-query'import { useRouter } from 'next/router'@@ -13,13 +12,16 @@ import { useProjectRestartMutation } from 'data/projects/project-restart-mutatioimport { useProjectRestartServicesMutation } from 'data/projects/project-restart-services-mutation'import { setProjectStatus } from 'data/projects/projects-query'import { useCheckPermissions, useFlag } from 'hooks'+import { ChevronDown } from 'lucide-react'import {Button,DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,- IconChevronDown,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'@@ -84,8 +86,8 @@ const RestartServerButton = () => {return (<>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild><div className="flex items-center"><Buttontype="default"@@ -106,7 +108,7 @@ const RestartServerButton = () => {<Buttontype="default"className="rounded-l-none px-[4px] py-[5px]"- icon={<IconChevronDown />}+ icon={<ChevronDown />}disabled={!canRestartProject}/></DropdownMenuTrigger>@@ -130,46 +132,21 @@ const RestartServerButton = () => {</DropdownMenu>)}</div>- </Tooltip.Trigger>- {project !== undefined && (!canRestartProject || !isProjectActive) && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- {!canRestartProject- ? 'You need additional permissions to restart this project'- : !isProjectActive- ? 'Unable to restart project as project is not active'- : ''}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ </TooltipTrigger_Shadcn_>+ {((project !== undefined && (!canRestartProject || !isProjectActive)) ||+ projectRestartDisabled) && (+ <TooltipContent_Shadcn_ side="bottom">+ {projectRestartDisabled+ ? 'Project restart is currently disabled'+ : !canRestartProject+ ? 'You need additional permissions to restart this project'+ : !isProjectActive+ ? 'Unable to restart project as project is not active'+ : ''}+ </TooltipContent_Shadcn_>)}- {projectRestartDisabled && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- Project restart is currently disabled- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ </Tooltip_Shadcn_>+<ConfirmModaldangervisible={serviceToRestart !== undefined}diff --git a/apps/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx b/apps/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsxindex 20c83cb729c..8aed37def99 100644--- a/apps/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx+++ b/apps/studio/components/interfaces/Settings/General/TransferProjectPanel/TransferProjectButton.tsx@@ -1,4 +1,3 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import Link from 'next/link'import { useEffect, useState } from 'react'@@ -6,8 +5,6 @@ import toast from 'react-hot-toast'import {Alert,Button,- IconAlertCircle,- IconInfo,IconLoader,IconShield,IconTool,@@ -17,6 +14,7 @@ import {Modal,} from 'ui'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useOrganizationsQuery } from 'data/organizations/organizations-query'import { useProjectTransferMutation } from 'data/projects/project-transfer-mutation'import { useProjectTransferPreviewQuery } from 'data/projects/project-transfer-preview-query'@@ -80,39 +78,23 @@ const TransferProjectButton = () => {return (<>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- onClick={toggle}- type="default"- disabled={!canTransferProject || disableProjectTransfer}- >- Transfer project- </Button>- </Tooltip.Trigger>- {(!canTransferProject || disableProjectTransfer) && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- 'border border-background', //border- ].join(' ')}- >- <span className="text-xs text-foreground">- {!canTransferProject- ? 'You need additional permissions to transfer this project'- : 'Project transfers are temporarily disabled, please try again later.'}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ type="default"+ onClick={toggle}+ disabled={!canTransferProject || disableProjectTransfer}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canTransferProject+ ? 'You need additional permissions to transfer this project'+ : 'Project transfers are temporarily disabled, please try again later.',+ },+ }}+ >+ Transfer project+ </ButtonTooltip><Modal- closableonCancel={() => toggle()}visible={isOpen}loading={isTransferring}diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsxindex e26212e371d..13c99a589ad 100644--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx@@ -1,3 +1,4 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { partition } from 'lodash'import { ChevronDown, Globe2, Loader2, Network } from 'lucide-react'@@ -12,16 +13,19 @@ import {DropdownMenuItem,DropdownMenuSeparator,DropdownMenuTrigger,+ cn,} from 'ui'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useLoadBalancersQuery } from 'data/read-replicas/load-balancers-query'import { Database, useReadReplicasQuery } from 'data/read-replicas/replicas-query'import {ReplicaInitializationStatus,useReadReplicasStatusesQuery,} from 'data/read-replicas/replicas-status-query'+import { useCheckPermissions } from 'hooks'import { AWS_REGIONS_KEYS } from 'lib/constants'import { timeout } from 'lib/helpers'import { useSubscriptionPageStateSnapshot } from 'state/subscription-page'@@ -52,6 +56,8 @@ const InstanceConfigurationUI = () => {const [selectedReplicaToDrop, setSelectedReplicaToDrop] = useState<Database>()const [selectedReplicaToRestart, setSelectedReplicaToRestart] = useState<Database>()+ const canManageReplicas = useCheckPermissions(PermissionAction.CREATE, 'projects')+const {data: loadBalancers,refetch: refetchLoadBalancers,@@ -217,13 +223,20 @@ const InstanceConfigurationUI = () => {<><div className="z-10 absolute top-4 right-4 flex items-center justify-center gap-x-2"><div className="flex items-center justify-center">- <Button+ <ButtonTooltiptype="default"- className={replicas.length > 0 ? 'rounded-r-none' : ''}+ disabled={!canManageReplicas}+ className={cn(replicas.length > 0 ? 'rounded-r-none' : '')}onClick={() => setShowNewReplicaPanel(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to deploy replicas',+ },+ }}>Deploy a new replica- </Button>+ </ButtonTooltip>{replicas.length > 0 && (<DropdownMenu><DropdownMenuTrigger asChild>diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsxindex 5f1fc65f7d4..060ba43c748 100644--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx@@ -1,11 +1,19 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import dayjs from 'dayjs'import { Database, DatabaseBackup, HelpCircle, Loader2, MoreVertical } from 'lucide-react'import Link from 'next/link'import { Handle, NodeProps, Position } from 'reactflow'import { useParams } from 'common'+import SparkBar from 'components/ui/SparkBar'+import {+ DatabaseInitEstimations,+ ReplicaInitializationStatus,+ useReadReplicasStatusesQuery,+} from 'data/read-replicas/replicas-status-query'import { formatDatabaseID } from 'data/read-replicas/replicas.utils'-import { BASE_PATH, PROJECT_STATUS } from 'lib/constants'+import { useCheckPermissions } from 'hooks'+import { BASE_PATH } from 'lib/constants'import {Badge,Button,@@ -27,14 +35,8 @@ import {REPLICA_STATUS,Region,} from './InstanceConfiguration.constants'-import {- DatabaseInitEstimations,- ReplicaInitializationStatus,- useReadReplicasStatusesQuery,-} from 'data/read-replicas/replicas-status-query'-import { ReadReplicaSetupError, ReadReplicaSetupProgress } from '@supabase/shared-types/out/events'-import SparkBar from 'components/ui/SparkBar'import { formatSeconds } from './InstanceConfiguration.utils'+import { TooltipContent } from '@radix-ui/react-tooltip'interface NodeData {id: string@@ -178,6 +180,7 @@ export const ReplicaNode = ({ data }: NodeProps<ReplicaNodeData>) => {} = dataconst { ref } = useParams()const created = dayjs(inserted_at).format('DD MMM YYYY')+ const canManageReplicas = useCheckPermissions(PermissionAction.CREATE, 'projects')const { data: databaseStatuses } = useReadReplicasStatusesQuery({ projectRef: ref })const { replicaInitializationStatus } =@@ -358,9 +361,24 @@ export const ReplicaNode = ({ data }: NodeProps<ReplicaNodeData>) => {{/* <DropdownMenuItem className="gap-x-2" onClick={() => onSelectResizeReplica()}>Resize replica</DropdownMenuItem> */}- <DropdownMenuItem className="gap-x-2" onClick={() => onSelectDropReplica()}>- Drop replica- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ className="gap-x-2 !pointer-events-auto"+ disabled={!canManageReplicas}+ onClick={() => {+ if (canManageReplicas) onSelectDropReplica()+ }}+ >+ Drop replica+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canManageReplicas && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to drop replicas+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu></div>diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsxindex 7d4ead1c749..3f21a1c8ca2 100644--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx@@ -1,6 +1,8 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import dayjs from 'dayjs'import { partition, uniqBy } from 'lodash'+import { MoreVertical } from 'lucide-react'import Link from 'next/link'import { useEffect, useState } from 'react'import {@@ -20,12 +22,16 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,ScrollArea,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,} from 'ui'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { Database, useReadReplicasQuery } from 'data/read-replicas/replicas-query'import { formatDatabaseID } from 'data/read-replicas/replicas.utils'+import { useCheckPermissions } from 'hooks'import { AWS_REGIONS_KEYS, BASE_PATH } from 'lib/constants'-import { MoreVertical } from 'lucide-react'import { AVAILABLE_REPLICA_REGIONS, REPLICA_STATUS } from './InstanceConfiguration.constants'import GeographyData from './MapData.json'@@ -51,6 +57,7 @@ const MapView = ({y: numberregion: { key: string; country?: string; name?: string }}>()+ const canManageReplicas = useCheckPermissions(PermissionAction.CREATE, 'projects')const { data } = useReadReplicasQuery({ projectRef: ref })const databases = data ?? []@@ -310,12 +317,22 @@ const MapView = ({>Restart replica</DropdownMenuItem>- <DropdownMenuItem- className="gap-x-2"- onClick={() => onSelectDropReplica(database)}- >- Drop replica- </DropdownMenuItem>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <DropdownMenuItem+ className="gap-x-2 !pointer-events-auto"+ disabled={!canManageReplicas}+ onClick={() => onSelectDropReplica(database)}+ >+ Drop replica+ </DropdownMenuItem>+ </TooltipTrigger_Shadcn_>+ {!canManageReplicas && (+ <TooltipContent_Shadcn_ side="left">+ You need additional permissions to drop replicas+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_></DropdownMenuContent></DropdownMenu>)}@@ -331,9 +348,19 @@ const MapView = ({databasesInSelectedRegion.length > 0 ? 'border-t' : ''}`}>- <Button type="default" onClick={() => onSelectDeployNewReplica(selectedRegion.key)}>+ <ButtonTooltip+ type="default"+ disabled={!canManageReplicas}+ onClick={() => onSelectDeployNewReplica(selectedRegion.key)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to deploy replicas',+ },+ }}+ >Deploy new replica here- </Button>+ </ButtonTooltip><Buttontype="default"onClick={() => {diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsxindex bcc8f73772c..4977604967c 100644--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubIntegrationConnectionForm.tsx@@ -1,5 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import { GitBranch, RotateCcw, Shield } from 'lucide-react'+import { ChevronDown, GitBranch, RotateCcw, Shield } from 'lucide-react'import { useRef, useState } from 'react'import { useForm } from 'react-hook-form'import toast from 'react-hot-toast'@@ -21,7 +21,6 @@ import {FormLabel_Shadcn_,Form_Shadcn_,IconCheck,- IconChevronDown,Input_Shadcn_,Label_Shadcn_,PopoverContent_Shadcn_,@@ -32,19 +31,24 @@ import {} from 'ui'import * as z from 'zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'import { useBranchesQuery } from 'data/branches/branches-query'import { useGitHubBranchesQuery } from 'data/integrations/github-branches-query'import { useGitHubConnectionUpdateMutation } from 'data/integrations/github-connection-update-mutation'import type { IntegrationProjectConnection } from 'data/integrations/integrations.types'-import { useSelectedOrganization, useSelectedProject } from 'hooks'+import { useCheckPermissions, useSelectedOrganization, useSelectedProject } from 'hooks'import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'interface GitHubIntegrationConnectionFormProps {+ disabled?: booleanconnection: IntegrationProjectConnection}-const GitHubIntegrationConnectionForm = ({ connection }: GitHubIntegrationConnectionFormProps) => {+const GitHubIntegrationConnectionForm = ({+ disabled,+ connection,+}: GitHubIntegrationConnectionFormProps) => {const org = useSelectedOrganization()const project = useSelectedProject()const [open, setOpen] = useState(false)@@ -52,6 +56,11 @@ const GitHubIntegrationConnectionForm = ({ connection }: GitHubIntegrationConnecconst isBranchingEnabled =project?.is_branch_enabled === true || project?.parent_project_ref !== undefined+ const canUpdateGitHubConnection = useCheckPermissions(+ PermissionAction.UPDATE,+ 'integrations.github_connections'+ )+const { data: githubBranches, isLoading: isLoadingBranches } = useGitHubBranchesQuery({connectionId: Number(connection.id),@@ -160,7 +169,7 @@ const GitHubIntegrationConnectionForm = ({ connection }: GitHubIntegrationConnecloading={isUpdatingProdBranch || isLoadingBranches}iconRight={<span className="grow flex justify-end">- <IconChevronDown className={''} />+ <ChevronDown size={14} /></span>}>@@ -233,11 +242,12 @@ const GitHubIntegrationConnectionForm = ({ connection }: GitHubIntegrationConnec<FormDescription_Shadcn_ className="text-xs text-foreground-lighter !mt-0 !mb-1">Total number of branches that can be automatically created for this connection.</FormDescription_Shadcn_>- <FormControl_Shadcn_ className="flex gap-3">+ <FormControl_Shadcn_ className="flex gap-3 items-center"><div className="relative"><Input_Shadcn_{...field}className="w-80"+ disabled={!canUpdateGitHubConnection}onKeyPress={(event) => {if (event.key === 'Escape') form.reset()}}@@ -286,10 +296,11 @@ const GitHubIntegrationConnectionForm = ({ connection }: GitHubIntegrationConnecPath in your repository where <code>supabase</code> directory for this connectionlives.</FormDescription_Shadcn_>- <FormControl_Shadcn_ className="flex gap-3">+ <FormControl_Shadcn_ className="flex gap-3 items-center"><div className="relative"><Input_Shadcn_{...field}+ disabled={!canUpdateGitHubConnection}className="w-80"onKeyPress={(event) => {if (event.key === 'Escape') form.reset()@@ -337,6 +348,7 @@ const GitHubIntegrationConnectionForm = ({ connection }: GitHubIntegrationConnec<FormControl_Shadcn_><SwitchclassName="mt-1"+ disabled={!canUpdateGitHubConnection}checked={field.value}onCheckedChange={(e) => {field.onChange(e)diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsxindex 42c92930fc5..8a158d3c594 100644--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GithubSection.tsx@@ -1,7 +1,8 @@-import { useParams } from 'common'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useCallback } from 'react'import toast from 'react-hot-toast'+import { useParams } from 'common'import { IntegrationConnectionItem } from 'components/interfaces/Integrations/IntegrationConnection'import { EmptyIntegrationConnection } from 'components/interfaces/Integrations/IntegrationPanels'import { Markdown } from 'components/interfaces/Markdown'@@ -11,13 +12,14 @@ import {ScaffoldSectionContent,ScaffoldSectionDetail,} from 'components/layouts/Scaffold'+import NoPermission from 'components/ui/NoPermission'import { useGitHubConnectionDeleteMutation } from 'data/integrations/github-connection-delete-mutation'import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'import type {IntegrationName,IntegrationProjectConnection,} from 'data/integrations/integrations.types'-import { useFlag, useSelectedOrganization, useSelectedProject } from 'hooks'+import { useCheckPermissions, useFlag, useSelectedOrganization, useSelectedProject } from 'hooks'import { useSidePanelsStateSnapshot } from 'state/side-panels'import { IntegrationImageHandler } from '../IntegrationsSettings'import GitHubIntegrationConnectionForm from './GitHubIntegrationConnectionForm'@@ -42,6 +44,19 @@ const GitHubSection = () => {const org = useSelectedOrganization()const sidePanelsStateSnapshot = useSidePanelsStateSnapshot()+ const canReadGitHubConnection = useCheckPermissions(+ PermissionAction.READ,+ 'integrations.github_connections'+ )+ const canCreateGitHubConnection = useCheckPermissions(+ PermissionAction.CREATE,+ 'integrations.github_connections'+ )+ const canUpdateGitHubConnection = useCheckPermissions(+ PermissionAction.UPDATE,+ 'integrations.github_connections'+ )+const { data: allConnections } = useGitHubConnectionsQuery({ organizationId: org?.id })const { mutateAsync: deleteGitHubConnection } = useGitHubConnectionDeleteMutation({@@ -84,86 +99,96 @@ const GitHubSection = () => {<IntegrationImageHandler title="github" /></ScaffoldSectionDetail><ScaffoldSectionContent>- <Markdown content={GitHubContentSectionTop} />-- {connections.length > 0 ? (- <ul className="flex flex-col">- {connections.map((connection) => (- <div key={connection.id} className="relative flex flex-col -gap-[1px] [&>li]:pb-0">- <IntegrationConnectionItem- showNode={false}- disabled={isBranch}- key={connection.id}- connection={{- id: String(connection.id),- added_by: {- id: String(connection.user?.id),- primary_email: connection.user?.primary_email ?? '',- username: connection.user?.username ?? '',- },- foreign_project_id: String(connection.repository.id),- supabase_project_ref: connection.project.ref,- organization_integration_id: 'unused',- inserted_at: connection.inserted_at,- updated_at: connection.updated_at,- metadata: {- name: connection.repository.name,- } as any,- }}- type={'GitHub' as IntegrationName}- onDeleteConnection={onDeleteGitHubConnection}- className="!rounded-b-none !mb-0"- />-- <div className="border-b border-l border-r rounded-b-lg">- <GitHubIntegrationConnectionForm- connection={{- id: String(connection.id),- added_by: {- id: String(connection.user?.id),- primary_email: connection.user?.primary_email ?? '',- username: connection.user?.username ?? '',- },- foreign_project_id: String(connection.repository.id),- supabase_project_ref: connection.project.ref,- organization_integration_id: 'unused',- inserted_at: connection.inserted_at,- updated_at: connection.updated_at,- metadata: {- name: connection.repository.name,- supabaseConfig: {- supabaseDirectory: connection.workdir,- supabaseChangesOnly: connection.supabase_changes_only,- branchLimit: connection.branch_limit,- },- } as any,- }}- />- </div>- </div>- ))}- </ul>- ) : hasAccessToBranching ? (- <EmptyIntegrationConnection- onClick={onAddGitHubConnection}- orgSlug={org?.slug}- showNode={false}- >- Add new project connection- </EmptyIntegrationConnection>+ {!canReadGitHubConnection ? (+ <NoPermission resourceText="view this organization's GitHub connections" />) : (- <p className="text-sm text-foreground-light">- Access to{' '}- <a- href="https://supabase.com/docs/guides/platform/branching"- target="_blank"- rel="noreferrer"- className="text-foreground"- >- branching- </a>{' '}- is required to add GitHub connections.- </p>+ <>+ <Markdown content={GitHubContentSectionTop} />+ {connections.length > 0 ? (+ <ul className="flex flex-col">+ {connections.map((connection) => (+ <div+ key={connection.id}+ className="relative flex flex-col -gap-[1px] [&>li]:pb-0"+ >+ <IntegrationConnectionItem+ showNode={false}+ disabled={isBranch || !canUpdateGitHubConnection}+ key={connection.id}+ connection={{+ id: String(connection.id),+ added_by: {+ id: String(connection.user?.id),+ primary_email: connection.user?.primary_email ?? '',+ username: connection.user?.username ?? '',+ },+ foreign_project_id: String(connection.repository.id),+ supabase_project_ref: connection.project.ref,+ organization_integration_id: 'unused',+ inserted_at: connection.inserted_at,+ updated_at: connection.updated_at,+ metadata: {+ name: connection.repository.name,+ } as any,+ }}+ type={'GitHub' as IntegrationName}+ onDeleteConnection={onDeleteGitHubConnection}+ className="!rounded-b-none !mb-0"+ />++ <div className="border-b border-l border-r rounded-b-lg">+ <GitHubIntegrationConnectionForm+ disabled={!canUpdateGitHubConnection}+ connection={{+ id: String(connection.id),+ added_by: {+ id: String(connection.user?.id),+ primary_email: connection.user?.primary_email ?? '',+ username: connection.user?.username ?? '',+ },+ foreign_project_id: String(connection.repository.id),+ supabase_project_ref: connection.project.ref,+ organization_integration_id: 'unused',+ inserted_at: connection.inserted_at,+ updated_at: connection.updated_at,+ metadata: {+ name: connection.repository.name,+ supabaseConfig: {+ supabaseDirectory: connection.workdir,+ supabaseChangesOnly: connection.supabase_changes_only,+ branchLimit: connection.branch_limit,+ },+ } as any,+ }}+ />+ </div>+ </div>+ ))}+ </ul>+ ) : hasAccessToBranching ? (+ <EmptyIntegrationConnection+ onClick={onAddGitHubConnection}+ orgSlug={org?.slug}+ showNode={false}+ disabled={!canCreateGitHubConnection}+ >+ Add new project connection+ </EmptyIntegrationConnection>+ ) : (+ <p className="text-sm text-foreground-light">+ Access to{' '}+ <a+ href="https://supabase.com/docs/guides/platform/branching"+ target="_blank"+ rel="noreferrer"+ className="text-foreground"+ >+ branching+ </a>{' '}+ is required to add GitHub connections.+ </p>+ )}+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Settings/Integrations/IntegrationsSettings.tsx b/apps/studio/components/interfaces/Settings/Integrations/IntegrationsSettings.tsxindex 022286c234c..1da254b3c9b 100644--- a/apps/studio/components/interfaces/Settings/Integrations/IntegrationsSettings.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/IntegrationsSettings.tsx@@ -1,11 +1,12 @@import Link from 'next/link'-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, IconAlertCircle } from 'ui'+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_ } from 'ui'import SidePanelGitHubRepoLinker from 'components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker'import SidePanelVercelProjectLinker from 'components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker'import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'import { useProjectByRef, useSelectedProject } from 'hooks'import { BASE_PATH } from 'lib/constants'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'import GitHubSection from './GithubIntegration/GithubSection'import VercelSection from './VercelIntegration/VercelSection'@@ -29,7 +30,7 @@ const IntegrationSettings = () => {{isBranch && (<ScaffoldContainer><Alert_Shadcn_ variant="default" className="mt-6">- <IconAlertCircle strokeWidth={2} />+ <WarningIcon /><AlertTitle_Shadcn_>You are currently on a preview branch of your project</AlertTitle_Shadcn_>diff --git a/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelIntegrationConnectionForm.tsx b/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelIntegrationConnectionForm.tsxindex d9c7248e9e7..2d644fd2e22 100644--- a/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelIntegrationConnectionForm.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelIntegrationConnectionForm.tsx@@ -20,9 +20,11 @@ import {} from 'ui'const VercelIntegrationConnectionForm = ({+ disabled,connection,integration,}: {+ disabled?: booleanconnection: IntegrationProjectConnectionintegration: Integration}) => {@@ -82,6 +84,7 @@ const VercelIntegrationConnectionForm = ({<FormItem_Shadcn_ className="space-y-0 flex gap-x-4"><FormControl_Shadcn_><Switch+ disabled={disabled}className="mt-1"checked={field.value}onCheckedChange={(e) => {@@ -106,6 +109,7 @@ const VercelIntegrationConnectionForm = ({<FormItem_Shadcn_ className="space-y-0 flex gap-x-4"><FormControl_Shadcn_><Switch+ disabled={disabled}className="mt-1"checked={field.value}onCheckedChange={(e) => {@@ -130,6 +134,7 @@ const VercelIntegrationConnectionForm = ({<FormItem_Shadcn_ className="space-y-0 flex gap-x-4"><FormControl_Shadcn_><Switch+ disabled={disabled}className="mt-1"checked={field.value}onCheckedChange={(e) => {diff --git a/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelSection.tsx b/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelSection.tsxindex 72c36ec7f85..4675b20a94f 100644--- a/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelSection.tsx+++ b/apps/studio/components/interfaces/Settings/Integrations/VercelIntegration/VercelSection.tsx@@ -1,8 +1,9 @@+import { ExternalLink } from 'lucide-react'import Link from 'next/link'import { useCallback, useMemo } from 'react'import toast from 'react-hot-toast'-import { Button, IconExternalLink, cn } from 'ui'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { IntegrationConnectionItem } from 'components/interfaces/Integrations/IntegrationConnection'import {EmptyIntegrationConnection,@@ -16,6 +17,7 @@ import {ScaffoldSectionContent,ScaffoldSectionDetail,} from 'components/layouts/Scaffold'+import NoPermission from 'components/ui/NoPermission'import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-org-only'import { useIntegrationsVercelInstalledConnectionDeleteMutation } from 'data/integrations/integrations-vercel-installed-connection-delete-mutation'import { useVercelProjectsQuery } from 'data/integrations/integrations-vercel-projects-query'@@ -23,10 +25,11 @@ import type {IntegrationName,IntegrationProjectConnection,} from 'data/integrations/integrations.types'-import { useSelectedOrganization, useSelectedProject } from 'hooks'+import { useCheckPermissions, useSelectedOrganization, useSelectedProject } from 'hooks'import { pluralize } from 'lib/helpers'import { getIntegrationConfigurationUrl } from 'lib/integration-utils'import { useSidePanelsStateSnapshot } from 'state/side-panels'+import { Button, cn } from 'ui'import { IntegrationImageHandler } from '../IntegrationsSettings'import VercelIntegrationConnectionForm from './VercelIntegrationConnectionForm'@@ -36,6 +39,19 @@ const VercelSection = ({ isProjectScoped }: { isProjectScoped: boolean }) => {const { data } = useOrgIntegrationsQuery({ orgSlug: org?.slug })const sidePanelsStateSnapshot = useSidePanelsStateSnapshot()+ const canReadVercelConnection = useCheckPermissions(+ PermissionAction.READ,+ 'integrations.vercel_connections'+ )+ const canCreateVercelConnection = useCheckPermissions(+ PermissionAction.CREATE,+ 'integrations.vercel_connections'+ )+ const canUpdateVercelConnection = useCheckPermissions(+ PermissionAction.UPDATE,+ 'integrations.vercel_connections'+ )+const isBranch = project?.parent_project_ref !== undefinedconst { mutate: deleteVercelConnection } = useIntegrationsVercelInstalledConnectionDeleteMutation(@@ -145,81 +161,91 @@ You can change the scope of the access for Supabase by configuring<IntegrationImageHandler title="vercel" /></ScaffoldSectionDetail><ScaffoldSectionContent>- <Markdown content={VercelContentSectionTop} />- {vercelIntegration ? (- <div key={vercelIntegration.id}>- <IntegrationInstallation title={'Vercel'} integration={vercelIntegration} />- {connections.length > 0 ? (- <>- <IntegrationConnectionHeader- title={ConnectionHeaderTitle}- markdown={`Repository connections for Vercel`}- />- <ul className="flex flex-col">- {connections.map((connection) => (- <div- key={connection.id}- className={cn(- isProjectScoped && 'relative flex flex-col -gap-[1px] [&>li]:pb-0'- )}- >- <IntegrationConnectionItem- connection={connection}- type={'Vercel' as IntegrationName}- onDeleteConnection={onDeleteVercelConnection}- className={cn(isProjectScoped && '!rounded-b-none !mb-0')}- />- {isProjectScoped ? (- <div className="relative pl-8 ml-6 border-l border-muted pb-6">- <div className="border-b border-l border-r rounded-b-lg">- <VercelIntegrationConnectionForm- connection={connection}- integration={vercelIntegration}- />- </div>+ {!canReadVercelConnection ? (+ <NoPermission resourceText="view this organization's Vercel connections" />+ ) : (+ <>+ <Markdown content={VercelContentSectionTop} />+ {vercelIntegration ? (+ <div key={vercelIntegration.id}>+ <IntegrationInstallation title={'Vercel'} integration={vercelIntegration} />+ {connections.length > 0 ? (+ <>+ <IntegrationConnectionHeader+ title={ConnectionHeaderTitle}+ markdown={`Repository connections for Vercel`}+ />+ <ul className="flex flex-col">+ {connections.map((connection) => (+ <div+ key={connection.id}+ className={cn(+ isProjectScoped && 'relative flex flex-col -gap-[1px] [&>li]:pb-0'+ )}+ >+ <IntegrationConnectionItem+ connection={connection}+ disabled={!canUpdateVercelConnection}+ type={'Vercel' as IntegrationName}+ onDeleteConnection={onDeleteVercelConnection}+ className={cn(isProjectScoped && '!rounded-b-none !mb-0')}+ />+ {isProjectScoped ? (+ <div className="relative pl-8 ml-6 border-l border-muted pb-6">+ <div className="border-b border-l border-r rounded-b-lg">+ <VercelIntegrationConnectionForm+ connection={connection}+ integration={vercelIntegration}+ disabled={!canUpdateVercelConnection}+ />+ </div>+ </div>+ ) : null}</div>- ) : null}- </div>- ))}- </ul>- </>+ ))}+ </ul>+ </>+ ) : (+ <IntegrationConnectionHeader+ title={ConnectionHeaderTitle}+ className="pb-0"+ markdown={`Repository connections for Vercel`}+ />+ )}+ <EmptyIntegrationConnection+ orgSlug={org?.slug}+ disabled={!canCreateVercelConnection}+ onClick={() => onAddVercelConnection(vercelIntegration.id)}+ >+ Add new project connection+ </EmptyIntegrationConnection>+ </div>) : (- <IntegrationConnectionHeader- title={ConnectionHeaderTitle}- markdown={`Repository connections for Vercel`}+ <div>+ <Button+ icon={<ExternalLink />}+ asChild={!isBranch}+ type="default"+ disabled={isBranch}+ >+ {isBranch ? (+ <p>Install Vercel Integration</p>+ ) : (+ <Link href={integrationUrl} target="_blank" rel="noreferrer">+ Install Vercel Integration+ </Link>+ )}+ </Button>+ </div>+ )}+ {VercelContentSectionBottom && (+ <Markdown+ extLinks+ content={VercelContentSectionBottom}+ className="text-foreground-lighter"/>)}- <EmptyIntegrationConnection- onClick={() => onAddVercelConnection(vercelIntegration.id)}- orgSlug={org?.slug}- >- Add new project connection- </EmptyIntegrationConnection>- </div>- ) : (- <div>- <Button- asChild={!isBranch}- type="default"- disabled={isBranch}- iconRight={<IconExternalLink />}- >- {isBranch ? (- <p>Install Vercel Integration</p>- ) : (- <Link href={integrationUrl} target="_blank" rel="noreferrer">- Install Vercel Integration- </Link>- )}- </Button>- </div>- )}- {VercelContentSectionBottom && (- <Markdown- extLinks- content={VercelContentSectionBottom}- className="text-foreground-lighter"- />+ </>)}</ScaffoldSectionContent></ScaffoldSection>diff --git a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsxindex d88581ab328..833f7a25f61 100644--- a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx+++ b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx@@ -375,7 +375,6 @@ const LogTable = ({rowHeight={40}headerRowHeight={queryType ? 0 : 28}onSelectedCellChange={(row) => {- console.log('row', row)setFocusedLog(row.row as LogData)}}selectedRows={new Set([])}diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsxindex 6f7916f720c..3a867565a3f 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice.tsx@@ -1,13 +1,21 @@-import { useParams } from 'common'+import { PermissionAction } from '@supabase/shared-types/out/constants'import Link from 'next/link'-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'+import { useParams } from 'common'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useCheckPermissions } from 'hooks'import { useAppStateSnapshot } from 'state/app-state'+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'const BranchingPITRNotice = () => {const { ref } = useParams()const snap = useAppStateSnapshot()+ const canUpdateSubscription = useCheckPermissions(+ PermissionAction.BILLING_WRITE,+ 'stripe.subscriptions'+ )+return (<Alert_Shadcn_ className="rounded-none px-7 py-6 [&>svg]:top-6 [&>svg]:left-6 !border-t-0 !border-l-0 !border-r-0"><AlertTitle_Shadcn_ className="text-base">@@ -17,14 +25,31 @@ const BranchingPITRNotice = () => {This is to ensure that you can always recover data if you make a "bad migration". Forexample, if you accidentally delete a column or some of your production data.</AlertDescription_Shadcn_>- <Button size="tiny" type="default" className="mt-4">- <Link- href={`/project/${ref}/settings/addons?panel=pitr`}- onClick={() => snap.setShowEnableBranchingModal(false)}+ {!canUpdateSubscription ? (+ <ButtonTooltip+ disabled+ size="tiny"+ type="default"+ className="mt-4"+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to amend subscriptions',+ },+ }}>Enable PITR add-on- </Link>- </Button>+ </ButtonTooltip>+ ) : (+ <Button size="tiny" type="default" className="mt-4">+ <Link+ href={`/project/${ref}/settings/addons?panel=pitr`}+ onClick={() => snap.setShowEnableBranchingModal(false)}+ >+ Enable PITR add-on+ </Link>+ </Button>+ )}</Alert_Shadcn_>)}diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsxindex c37ce84e2b9..97e02cf3534 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingButton.tsx@@ -1,12 +1,8 @@-import {- Button,- IconGitBranch,- TooltipContent_Shadcn_,- TooltipTrigger_Shadcn_,- Tooltip_Shadcn_,-} from 'ui'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { GitBranch } from 'lucide-react'-import { useFlag, useSelectedProject } from 'hooks'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useCheckPermissions, useFlag, useSelectedProject } from 'hooks'import { useAppStateSnapshot } from 'state/app-state'import BranchingWaitListPopover from './BranchingWaitListPopover'@@ -19,29 +15,35 @@ const EnableBranchingButton = ({ isNewNav = false }: EnableBranchingButtonProps)const project = useSelectedProject()const hasAccessToBranching = useFlag<boolean>('branchManagement')+ const canEnableBranching = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {+ resource: { is_default: true },+ })+ const isDisabled = !canEnableBranching || project?.status !== 'ACTIVE_HEALTHY'if (!hasAccessToBranching) {return <BranchingWaitListPopover isNewNav={isNewNav} />}return (- <Tooltip_Shadcn_>- <TooltipTrigger_Shadcn_ asChild>- <Button- type={isNewNav ? 'default' : 'text'}- icon={<IconGitBranch strokeWidth={1.5} />}- disabled={project?.status !== 'ACTIVE_HEALTHY'}- onClick={() => snap.setShowEnableBranchingModal(true)}- >- Enable branching- </Button>- </TooltipTrigger_Shadcn_>- {project?.status !== 'ACTIVE_HEALTHY' && (- <TooltipContent_Shadcn_ side="bottom">- Unpause your project to enable branching- </TooltipContent_Shadcn_>- )}- </Tooltip_Shadcn_>+ <ButtonTooltip+ disabled={isDisabled}+ type={isNewNav ? 'default' : 'text'}+ icon={<GitBranch strokeWidth={1.5} />}+ onClick={() => snap.setShowEnableBranchingModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text:+ project?.status !== 'ACTIVE_HEALTHY'+ ? 'Unpause your project to enable branching'+ : !canEnableBranching+ ? 'You need additional permissions to enable branching'+ : undefined,+ },+ }}+ >+ Enable branching+ </ButtonTooltip>)}diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsxindex d04449cfc28..43b79e929b6 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/EnableBranchingModal.tsx@@ -5,15 +5,7 @@ import Link from 'next/link'import { useEffect, useState } from 'react'import { useForm } from 'react-hook-form'import toast from 'react-hot-toast'-import {- Button,- Form_Shadcn_,- IconDollarSign,- IconExternalLink,- IconFileText,- IconGitBranch,- Modal,-} from 'ui'+import { Button, Form_Shadcn_, IconExternalLink, IconGitBranch, Modal } from 'ui'import * as z from 'zod'import SidePanelGitHubRepoLinker from 'components/interfaces/Organization/IntegrationSettings/SidePanelGitHubRepoLinker'@@ -25,12 +17,14 @@ import { useCheckGithubBranchValidity } from 'data/integrations/github-branch-chimport { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'-import { useSelectedOrganization } from 'hooks'+import { useCheckPermissions, useSelectedOrganization } from 'hooks'+import { DollarSign, FileText } from 'lucide-react'import { useAppStateSnapshot } from 'state/app-state'import BranchingPITRNotice from './BranchingPITRNotice'import BranchingPlanNotice from './BranchingPlanNotice'import BranchingPostgresVersionNotice from './BranchingPostgresVersionNotice'import GithubRepositorySelection from './GithubRepositorySelection'+import { PermissionAction } from '@supabase/shared-types/out/constants'const EnableBranchingModal = () => {const { ref } = useParams()@@ -42,6 +36,8 @@ const EnableBranchingModal = () => {// and makes the validation run onChange instead. This is a workaroundconst [isValid, setIsValid] = useState(false)+ const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches')+const {data: connections,error: connectionsError,@@ -215,7 +211,7 @@ const EnableBranchingModal = () => {<div className="flex flex-row gap-4"><div><figure className="w-10 h-10 rounded-md bg-warning-200 border border-warning-400 flex items-center justify-center">- <IconDollarSign className="text-warning" size={20} strokeWidth={2} />+ <DollarSign className="text-warning" size={20} strokeWidth={2} /></figure></div><div className="flex flex-col gap-y-1">@@ -232,7 +228,7 @@ const EnableBranchingModal = () => {<div className="flex flex-row gap-4 mt-2"><div><figure className="w-10 h-10 rounded-md bg-warning-200 border border-warning-400 flex items-center justify-center">- <IconFileText className="text-warning" size={20} strokeWidth={2} />+ <FileText className="text-warning" size={20} strokeWidth={2} /></figure></div><div className="flex flex-col gap-y-1">diff --git a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsx b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsxindex 3f0172a0298..d5354564da6 100644--- a/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsx+++ b/apps/studio/components/layouts/AppLayout/EnableBranchingButton/GithubRepositorySelection.tsx@@ -5,6 +5,7 @@ import {} from 'components/interfaces/Integrations/IntegrationPanels'import type { GitHubConnection } from 'data/integrations/github-connections-query'import { useSelectedOrganization } from 'hooks'+import { Check, Loader2 } from 'lucide-react'import { useSidePanelsStateSnapshot } from 'state/side-panels'import {Badge,@@ -90,7 +91,7 @@ const GithubRepositorySelection = ({control={form.control}name="branchName"render={({ field }) => (- <FormItem_Shadcn_ className="relative">+ <FormItem_Shadcn_ className="flex flex-col gap-y-1 relative"><label className="text-sm text-foreground-light">Choose your production branch</label>@@ -99,9 +100,9 @@ const GithubRepositorySelection = ({</FormControl_Shadcn_><div className="absolute top-9 right-3">{isChecking ? (- <IconLoader className="animate-spin" />+ <Loader2 size={14} className="animate-spin" />) : isValid ? (- <IconCheck className="text-brand" strokeWidth={2} />+ <Check size={14} className="text-brand" strokeWidth={2} />) : null}</div>diff --git a/apps/studio/components/layouts/LogsLayout/LogsLayout.tsx b/apps/studio/components/layouts/LogsLayout/LogsLayout.tsxindex e95f8d1f50b..a1c7220b727 100644--- a/apps/studio/components/layouts/LogsLayout/LogsLayout.tsx+++ b/apps/studio/components/layouts/LogsLayout/LogsLayout.tsx@@ -2,8 +2,13 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { useRouter } from 'next/router'import { PropsWithChildren } from 'react'+import { useParams } from 'common'+import { CreateWarehouseCollectionModal } from 'components/interfaces/DataWarehouse/CreateWarehouseCollection'+import { WarehouseMenuItem } from 'components/interfaces/DataWarehouse/WarehouseMenuItem'import NoPermission from 'components/ui/NoPermission'import { ProductMenu } from 'components/ui/ProductMenu'+import { useWarehouseCollectionsQuery } from 'data/analytics/warehouse-collections-query'+import { useWarehouseTenantQuery } from 'data/analytics/warehouse-tenant-query'import {useCheckPermissions,useFlag,@@ -11,16 +16,10 @@ import {useSelectedProject,withAuth,} from 'hooks'-import { ProjectLayout } from '../'-import { generateLogsMenu } from './LogsMenu.utils'import { Badge, Menu } from 'ui'-import ShimmeringLoader from 'components/ui/ShimmeringLoader'-import { CreateWarehouseCollectionModal } from 'components/interfaces/DataWarehouse/CreateWarehouseCollection'-import { WarehouseMenuItem } from 'components/interfaces/DataWarehouse/WarehouseMenuItem'-import { useWarehouseCollectionsQuery } from 'data/analytics/warehouse-collections-query'-import { useWarehouseTenantQuery } from 'data/analytics/warehouse-tenant-query'-import { useParams } from 'common'import { GenericSkeletonLoader } from 'ui-patterns'+import { ProjectLayout } from '../'+import { generateLogsMenu } from './LogsMenu.utils'interface LogsLayoutProps {title?: string}diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectPausedState.tsxindex 77639de8e07..b1f2953caa4 100644--- a/apps/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/ProjectPausedState.tsx@@ -1,5 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQueryClient } from '@tanstack/react-query'+import dayjs from 'dayjs'import { Download, PauseCircle } from 'lucide-react'import Link from 'next/link'import { useState } from 'react'@@ -7,13 +8,13 @@ import toast from 'react-hot-toast'import { useParams } from 'common'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { useBackupDownloadMutation } from 'data/database/backup-download-mutation'import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'import { useProjectPauseStatusQuery } from 'data/projects/project-pause-status-query'import { useProjectRestoreMutation } from 'data/projects/project-restore-mutation'import { setProjectStatus } from 'data/projects/projects-query'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'-import dayjs from 'dayjs'import { useCheckPermissions, useFlag, useSelectedOrganization } from 'hooks'import { PROJECT_STATUS } from 'lib/constants'import {@@ -252,24 +253,20 @@ const ProjectPausedState = ({ product }: ProjectPausedStateProps) => {{(!enforceNinetyDayUnpauseExpiry || (isSuccess && !isRestoreDisabled)) && (<div className="flex items-center justify-center gap-4">- <Tooltip_Shadcn_>- <TooltipTrigger_Shadcn_ asChild>- <Button- size="tiny"- type="default"- className="pointer-events-auto"- disabled={!canResumeProject}- onClick={onSelectRestore}- >- Restore project- </Button>- </TooltipTrigger_Shadcn_>- {!canResumeProject && (- <TooltipContent_Shadcn_ side="bottom">- You need additional permissions to resume this project- </TooltipContent_Shadcn_>- )}- </Tooltip_Shadcn_>+ <ButtonTooltip+ size="tiny"+ type="default"+ disabled={!canResumeProject}+ onClick={onSelectRestore}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to resume this project',+ },+ }}+ >+ Restore project+ </ButtonTooltip>{isFreePlan ? (<Button asChild type="primary"><Link href={`/org/${orgSlug}/billing?panel=subscriptionPlan`}>diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsxindex 52ddfeffdad..74e9c4f573d 100644--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx@@ -1,3 +1,4 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { ChevronDown, Edit2, Plus, Trash } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'@@ -7,10 +8,12 @@ import toast from 'react-hot-toast'import { useParams } from 'common'import { CreateReportModal } from 'components/interfaces/Reports/Reports.CreateReportModal'import { UpdateCustomReportModal } from 'components/interfaces/Reports/Reports.UpdateModal'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useContentDeleteMutation } from 'data/content/content-delete-mutation'import { Content, useContentQuery } from 'data/content/content-query'-import { useIsFeatureEnabled } from 'hooks'+import { useCheckPermissions, useIsFeatureEnabled } from 'hooks'+import { useProfile } from 'lib/profile'import {AlertDescription_Shadcn_,AlertTitle_Shadcn_,@@ -28,10 +31,20 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'const ReportsMenu = () => {const router = useRouter()+ const { profile } = useProfile()const { ref, id } = useParams()const pageKey = (id || router.pathname.split('/')[4]) as stringconst storageEnabled = useIsFeatureEnabled('project_storage:all')+ const canCreateCustomReport = useCheckPermissions(PermissionAction.CREATE, 'user_content', {+ resource: { type: 'report', owner_id: profile?.id },+ subject: { id: profile?.id },+ })+ const canUpdateCustomReport = useCheckPermissions(PermissionAction.UPDATE, 'user_content', {+ resource: { type: 'report', owner_id: profile?.id },+ subject: { id: profile?.id },+ })+const { data: content, isLoading } = useContentQuery(ref)const { mutate: deleteReport, isLoading: isDeleting } = useContentDeleteMutation({onSuccess: () => {@@ -124,17 +137,25 @@ const ReportsMenu = () => {</div>) : (<div className="flex flex-col px-2 gap-y-6">- <div className="flex px-2">- <Button+ <div className="px-2">+ <ButtonTooltip+ blocktype="default"+ icon={<Plus />}+ disabled={!canCreateCustomReport}className="justify-start flex-grow"onClick={() => {setShowNewReportModal(true)}}- icon={<Plus size={12} />}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create custom reports',+ },+ }}>New custom report- </Button>+ </ButtonTooltip></div>{reportMenuItems.length > 0 ? (@@ -154,37 +175,39 @@ const ReportsMenu = () => {><div>{item.name}</div>- <DropdownMenu>- <DropdownMenuTrigger>- <Button- type="text"- className="px-1 opacity-50 hover:opacity-100"- icon={<ChevronDown size={12} strokeWidth={2} />}- />- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-52 *:space-x-2">- <DropdownMenuItem- onClick={() => {- if (!item.id) return- setSelectedReportToUpdate(item.report)- }}- >- <Edit2 size={12} />- <div>Rename</div>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={async () => {- if (!item.id) return- setSelectedReportToDelete(item.report)- setDeleteModalOpen(true)- }}- >- <Trash size={12} />- <div>Delete</div>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ {canUpdateCustomReport && (+ <DropdownMenu>+ <DropdownMenuTrigger>+ <Button+ type="text"+ className="px-1 opacity-50 hover:opacity-100"+ icon={<ChevronDown size={12} strokeWidth={2} />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-52 *:space-x-2">+ <DropdownMenuItem+ onClick={() => {+ if (!item.id) return+ setSelectedReportToUpdate(item.report)+ }}+ >+ <Edit2 size={12} />+ <div>Rename</div>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={async () => {+ if (!item.id) return+ setSelectedReportToDelete(item.report)+ setDeleteModalOpen(true)+ }}+ >+ <Trash size={12} />+ <div>Delete</div>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</Link>))}</div>diff --git a/apps/studio/components/layouts/Scaffold.tsx b/apps/studio/components/layouts/Scaffold.tsxindex 4ea62a2b025..d5ef8d85c21 100644--- a/apps/studio/components/layouts/Scaffold.tsx+++ b/apps/studio/components/layouts/Scaffold.tsx@@ -2,7 +2,7 @@ import React from 'react'import { cn } from 'ui'const maxWidthClasses = 'mx-auto w-full max-w-[1600px]'-const paddingClasses = 'px-6 lg:px-14 xl:px-28 2xl:px-32'+const paddingClasses = 'px-6 lg:px-14 xl:px-24 2xl:px-32'const maxWidthClassesColumn = 'min-w-[420px]'const ScaffoldHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(diff --git a/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx b/apps/studio/components/layouts/StorageLayout/StorageMenu.tsxindex 3a872ec1545..b877fcdfacf 100644--- a/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx+++ b/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx@@ -1,5 +1,5 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { ArrowUpRight, Edit } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'import { useState } from 'react'@@ -10,11 +10,11 @@ import EditBucketModal from 'components/interfaces/Storage/EditBucketModal'import type { StorageBucket } from 'components/interfaces/Storage/Storage.types'import { DeleteBucketModal } from 'components/to-be-cleaned/Storage'import { EmptyBucketModal } from 'components/to-be-cleaned/Storage/EmptyBucketModal'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import ShimmeringLoader from 'components/ui/ShimmeringLoader'import { useBucketsQuery } from 'data/storage/buckets-query'import { useCheckPermissions, useSelectedProject } from 'hooks'-import { ArrowUpRight, Edit } from 'lucide-react'-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, Menu } from 'ui'+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Menu } from 'ui'import BucketRow from './BucketRow'const StorageMenu = () => {@@ -42,46 +42,28 @@ const StorageMenu = () => {return (<>- <Menu type="pills" className="my-6 flex flex-grow flex-col px-5">- <div className="mb-6 px-2">- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full">- <Button- block- type="default"- icon={- <div className="text-foreground-light">- <Edit size={14} />- </div>- }- disabled={!canCreateBuckets}- style={{ justifyContent: 'start' }}- onClick={() => setShowCreateBucketModal(true)}- >- New bucket- </Button>- </Tooltip.Trigger>- {!canCreateBuckets && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to create buckets- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <Menu type="pills" className="my-6 flex flex-grow flex-col">+ <div className="mb-6 mx-5">+ <ButtonTooltip+ block+ type="default"+ icon={<Edit size={14} />}+ disabled={!canCreateBuckets}+ style={{ justifyContent: 'start' }}+ onClick={() => setShowCreateBucketModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create buckets',+ },+ }}+ >+ New bucket+ </ButtonTooltip></div>+<div className="space-y-6">- <div>+ <div className="mx-3"><Menu.Group title={<span className="uppercase font-mono">All buckets</span>} />{isLoading && (@@ -138,8 +120,10 @@ const StorageMenu = () => {</>)}</div>- <div className="h-px w-full bg-border"></div>- <div>++ <div className="h-px w-full bg-border" />++ <div className="mx-3"><Menu.Group title={<span className="uppercase font-mono">Configuration</span>} /><Link href={`/project/${ref}/storage/policies`} legacyBehavior><Menu.Item rounded active={page === 'policies'}>diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsxindex 622bebd8df9..10aa6e8e243 100644--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx@@ -7,13 +7,12 @@ import { ProjectLayoutWithAuth } from '../ProjectLayout/ProjectLayout'import TableEditorMenu from './TableEditorMenu'const TableEditorLayout = ({ children }: PropsWithChildren<{}>) => {- const canReadTables = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'tables')const isPermissionsLoaded = usePermissionsLoaded()+ const canReadTables = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'tables')const tableEditorMenu = useMemo(() => <TableEditorMenu />, [])if (isPermissionsLoaded && !canReadTables) {- debuggerreturn (<ProjectLayoutWithAuth isBlocking={false}><NoPermission isFullPage resourceText="view tables from this project" />diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsxindex 24ebd09141b..2c76b33cccd 100644--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx@@ -1,4 +1,3 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import { partition } from 'lodash'import { Filter, Plus } from 'lucide-react'@@ -8,6 +7,7 @@ import { useMemo, useState } from 'react'import { useParams } from 'common'import { ProtectedSchemaModal } from 'components/interfaces/Database/ProtectedSchemaWarning'import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import InfiniteList from 'components/ui/InfiniteList'import SchemaSelector from 'components/ui/SchemaSelector'import { useSchemasQuery } from 'data/database/schemas-query'@@ -120,40 +120,25 @@ const TableEditorMenu = () => {<div className="grid gap-3 mx-4">{!isLocked ? (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger className="w-full" asChild>- <Button- title="Create a new table"- name="New table"- block- disabled={!canCreateTables}- size="tiny"- icon={<Plus size={14} strokeWidth={1.5} className="text-foreground-muted" />}- type="default"- className="justify-start"- onClick={snap.onAddTable}- >- New table- </Button>- </Tooltip.Trigger>- {!canCreateTables && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">- You need additional permissions to create tables- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- )}- </Tooltip.Root>+ <ButtonTooltip+ block+ title="Create a new table"+ name="New table"+ disabled={!canCreateTables}+ size="tiny"+ icon={<Plus size={14} strokeWidth={1.5} className="text-foreground-muted" />}+ type="default"+ className="justify-start"+ onClick={snap.onAddTable}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to create tables',+ },+ }}+ >+ New table+ </ButtonTooltip>) : (<Alert_Shadcn_><AlertTitle_Shadcn_ className="text-sm">diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/CreateCredentialModal.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/CreateCredentialModal.tsxindex 7d2f1af98ef..dfb1e205430 100644--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/CreateCredentialModal.tsx+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/CreateCredentialModal.tsx@@ -1,4 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useState } from 'react'import { useForm } from 'react-hook-form'import { z } from 'zod'@@ -7,6 +8,7 @@ import { FormField } from '@ui/components/shadcn/ui/form'import { useParams } from 'common'import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'import { useS3AccessKeyCreateMutation } from 'data/storage/s3-access-key-create-mutation'+import { useCheckPermissions } from 'hooks'import {Button,Dialog,@@ -36,6 +38,8 @@ export const CreateCredentialModal = ({ visible, onOpenChange }: CreateCredentiaconst isProjectActive = useIsProjectActive()const [showSuccess, setShowSuccess] = useState(false)+ const canCreateCredentials = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')+const FormSchema = z.object({description: z.string().min(3, {message: 'Description must be at least 3 characters long',@@ -74,14 +78,22 @@ export const CreateCredentialModal = ({ visible, onOpenChange }: CreateCredentia<Tooltip_Shadcn_><TooltipTrigger_Shadcn_ asChild><DialogTrigger asChild>- <Button type="default" disabled={!isProjectActive}>+ <Button+ type="default"+ disabled={!isProjectActive || !canCreateCredentials}+ className="pointer-events-auto"+ >New access key</Button></DialogTrigger></TooltipTrigger_Shadcn_>- {!isProjectActive && (- <TooltipContent_Shadcn_>- Restore your project to create new access keys+ {(!isProjectActive || !canCreateCredentials) && (+ <TooltipContent_Shadcn_ side="bottom">+ {!isProjectActive+ ? 'Restore your project to create new access keys'+ : !canCreateCredentials+ ? 'You need additional permissions to create new access keys'+ : ''}</TooltipContent_Shadcn_>)}</Tooltip_Shadcn_>diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsxindex 4bbdd85b473..2dba993b390 100644--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx@@ -1,3 +1,4 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { AlertTitle } from '@ui/components/shadcn/ui/alert'import Link from 'next/link'import { useState } from 'react'@@ -9,10 +10,12 @@ import {} from 'components/layouts/ProjectLayout/ProjectContext'import Table from 'components/to-be-cleaned/Table'import { FormHeader } from 'components/ui/Forms'+import NoPermission from 'components/ui/NoPermission'import Panel from 'components/ui/Panel'import { useProjectApiQuery } from 'data/config/project-api-query'import { useStorageCredentialsQuery } from 'data/storage/s3-access-key-query'-import { AlertDescription_Shadcn_, Alert_Shadcn_, Button, cn } from 'ui'+import { useCheckPermissions } from 'hooks'+import { AlertDescription_Shadcn_, Alert_Shadcn_, Button } from 'ui'import { GenericSkeletonLoader } from 'ui-patterns'import { Input } from 'ui-patterns/DataInputs/Input'import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'@@ -31,10 +34,13 @@ export const S3Connection = () => {const [openDeleteDialog, setOpenDeleteDialog] = useState(false)const [deleteCred, setDeleteCred] = useState<{ id: string; description: string }>()+ const canReadS3Credentials = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')+const { data: projectAPI } = useProjectApiQuery({ projectRef: projectRef })- const { data: storageCreds, ...storageCredsQuery } = useStorageCredentialsQuery({- projectRef,- })+ const { data: storageCreds, ...storageCredsQuery } = useStorageCredentialsQuery(+ { projectRef },+ { enabled: canReadS3Credentials }+ )const hasStorageCreds = storageCreds?.data && storageCreds.data.length > 0const s3connectionUrl = getConnectionURL(projectRef ?? '', projectAPI)@@ -85,7 +91,9 @@ export const S3Connection = () => {}/>- {projectIsLoading ? (+ {!canReadS3Credentials ? (+ <NoPermission resourceText="view this project's S3 access keys" />+ ) : projectIsLoading ? (<GenericSkeletonLoader />) : !isProjectActive ? (<Alert_Shadcn_ variant="warning">diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageCredItem.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageCredItem.tsxindex e56366eb80f..201e70ede05 100644--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageCredItem.tsx+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageCredItem.tsx@@ -1,7 +1,9 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { differenceInDays } from 'date-fns'import { MoreVertical, TrashIcon } from 'lucide-react'import CopyButton from 'components/ui/CopyButton'+import { useCheckPermissions } from 'hooks'import {Button,DropdownMenu,@@ -23,6 +25,8 @@ export const StorageCredItem = ({access_key: stringonDeleteClick: (id: string) => void}) => {+ const canRemoveAccessKey = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')+function daysSince(date: string) {const now = new Date()const created = new Date(date)@@ -52,27 +56,29 @@ export const StorageCredItem = ({</td><td>{daysSince(created_at)}</td><td className="text-right">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- icon={<MoreVertical size={14} strokeWidth={1} />}- type="text"- className="px-1.5 text-foreground-lighter hover:text-foreground"- ></Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="max-w-40" align="end">- <DropdownMenuItem- className="flex gap-1.5 "- onClick={(e) => {- e.preventDefault()- onDeleteClick(id)- }}- >- <TrashIcon size="14" />- Revoke key- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ {canRemoveAccessKey && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ icon={<MoreVertical size={14} strokeWidth={1} />}+ type="text"+ className="px-1.5 text-foreground-lighter hover:text-foreground"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="max-w-40" align="end">+ <DropdownMenuItem+ className="flex gap-1.5 "+ onClick={(e) => {+ e.preventDefault()+ onDeleteClick(id)+ }}+ >+ <TrashIcon size="14" />+ Revoke key+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</td></tr>)diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsxindex df2960c61a9..672078e348f 100644--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.tsx@@ -8,6 +8,7 @@ import * as z from 'zod'import { useParams } from 'common'import AlertError from 'components/ui/AlertError'+import NoPermission from 'components/ui/NoPermission'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import UpgradeToPro from 'components/ui/UpgradeToPro'import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'@@ -34,6 +35,7 @@ import { convertFromBytes, convertToBytes } from './StorageSettings.utils'const StorageSettings = () => {const { ref: projectRef } = useParams()+ const canReadStorageSettings = useCheckPermissions(PermissionAction.STORAGE_ADMIN_READ, '*')const canUpdateStorageSettings = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')const {@@ -105,134 +107,141 @@ const StorageSettings = () => {const formId = 'storage-settings-form'+ if (!canReadStorageSettings) {+ return <NoPermission resourceText="view storage upload limit settings" />+ }+return (- <div>- <Form_Shadcn_ {...form}>- {isLoading && <GenericSkeletonLoader />}- {isError && (- <AlertError error={error} subject="Failed to retrieve project's storage configuration" />- )}- {isSuccess && (- <form id={formId} className="" onSubmit={form.handleSubmit(onSubmit)}>- <div className="bg-surface-100 overflow-hidden border-muted rounded-md border shadow">- <div className="flex flex-col gap-0 divide-y divide-border-muted">- <div className="grid grid-cols-12 gap-6 px-8 py-8 lg:gap-12">- <div className="relative flex flex-col col-span-12 gap-6 lg:col-span-4">- <p className="text-sm">Upload file size limit</p>- </div>+ <Form_Shadcn_ {...form}>+ {isLoading && <GenericSkeletonLoader />}+ {isError && (+ <AlertError error={error} subject="Failed to retrieve project's storage configuration" />+ )}+ {isSuccess && (+ <form id={formId} className="" onSubmit={form.handleSubmit(onSubmit)}>+ <div className="bg-surface-100 overflow-hidden border-muted rounded-md border shadow">+ <div className="flex flex-col gap-0 divide-y divide-border-muted">+ <div className="grid grid-cols-12 gap-6 px-8 py-8 lg:gap-12">+ <div className="relative flex flex-col col-span-12 gap-6 lg:col-span-4">+ <p className="text-sm">Upload file size limit</p>+ </div>- <div className="relative flex flex-col col-span-12 gap-x-6 gap-y-2 lg:col-span-8">- <div className="grid grid-cols-12 col-span-12 gap-2">- <div className="col-span-8">- <FormField_Shadcn_- control={form.control}- name="fileSizeLimit"- render={({ field }) => (- <FormItem_Shadcn_>- <FormLabel_Shadcn_ className="text-foreground-light hidden">- size- </FormLabel_Shadcn_>- <FormControl_Shadcn_ className="col-span-8">- <Input_Shadcn_ type="number" {...field} className="w-full" />- </FormControl_Shadcn_>- <FormMessage_Shadcn_ className="col-start-5 col-span-8" />- </FormItem_Shadcn_>- )}- />- </div>- <div className="col-span-4">- <FormField_Shadcn_- control={form.control}- name="unit"- render={({ field }) => (- <FormItem_Shadcn_>- <FormLabel_Shadcn_ className="hidden">Unit</FormLabel_Shadcn_>- <FormControl_Shadcn_ className="col-span-8">- <Select_Shadcn_- disabled={isFreeTier}- value={field.value}- onValueChange={field.onChange}- >- <SelectTrigger_Shadcn_ className="w-[180px]">- <SelectValue_Shadcn_ placeholder="Choose a prefix">- {storageUnit}- </SelectValue_Shadcn_>- </SelectTrigger_Shadcn_>- <SelectContent_Shadcn_>- {Object.values(StorageSizeUnits).map((unit: string) => (- <SelectItem_Shadcn_- key={unit}- disabled={isFreeTier}- value={unit}- >- {unit}- </SelectItem_Shadcn_>- ))}- </SelectContent_Shadcn_>- </Select_Shadcn_>- </FormControl_Shadcn_>- <FormMessage_Shadcn_ />- </FormItem_Shadcn_>- )}- />- </div>+ <div className="relative flex flex-col col-span-12 gap-x-6 gap-y-2 lg:col-span-8">+ <div className="grid grid-cols-12 col-span-12 gap-2 items-center">+ <div className="col-span-8">+ <FormField_Shadcn_+ control={form.control}+ name="fileSizeLimit"+ render={({ field }) => (+ <FormItem_Shadcn_>+ <FormLabel_Shadcn_ className="text-foreground-light hidden">+ size+ </FormLabel_Shadcn_>+ <FormControl_Shadcn_ className="col-span-8">+ <Input_Shadcn_+ type="number"+ {...field}+ className="w-full"+ disabled={!canUpdateStorageSettings}+ />+ </FormControl_Shadcn_>+ <FormMessage_Shadcn_ className="col-start-5 col-span-8" />+ </FormItem_Shadcn_>+ )}+ />+ </div>+ <div className="col-span-4">+ <FormField_Shadcn_+ control={form.control}+ name="unit"+ render={({ field }) => (+ <FormItem_Shadcn_>+ <FormLabel_Shadcn_ className="hidden">Unit</FormLabel_Shadcn_>+ <FormControl_Shadcn_ className="col-span-8">+ <Select_Shadcn_+ value={field.value}+ onValueChange={field.onChange}+ disabled={isFreeTier || !canUpdateStorageSettings}+ >+ <SelectTrigger_Shadcn_ className="w-[180px]">+ <SelectValue_Shadcn_ placeholder="Choose a prefix">+ {storageUnit}+ </SelectValue_Shadcn_>+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {Object.values(StorageSizeUnits).map((unit: string) => (+ <SelectItem_Shadcn_+ key={unit}+ disabled={isFreeTier}+ value={unit}+ >+ {unit}+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ <FormMessage_Shadcn_ />+ </FormItem_Shadcn_>+ )}+ /></div>- <p className="text-sm text-foreground-light">- {storageUnit !== StorageSizeUnits.BYTES &&- `Equivalent to ${convertToBytes(- limit,- storageUnit- ).toLocaleString()} bytes. `}- Maximum size in bytes of a file that can be uploaded is 50 GB (- {formattedMaxSizeBytes}).- </p></div>+ <p className="text-sm text-foreground-light">+ {storageUnit !== StorageSizeUnits.BYTES &&+ `Equivalent to ${convertToBytes(+ limit,+ storageUnit+ ).toLocaleString()} bytes. `}+ Maximum size in bytes of a file that can be uploaded is 50 GB (+ {formattedMaxSizeBytes}).+ </p></div></div>- {isFreeTier && (- <div className="px-6 pb-6">- <UpgradeToPro- icon={<Clock size={14} className="text-foreground-muted" />}- primaryText="Free Plan has a fixed upload file size limit of 50 MB."- secondaryText="Upgrade to the Pro plan for a configurable upload file size limit of up to 50 GB."- />- </div>- )}- <div className="border-t border-overlay" />- <div className="flex justify-between px-8 py-4">- <div className="flex items-center justify-between w-full gap-2">- {!canUpdateStorageSettings ? (- <p className="text-sm text-foreground-light">- You need additional permissions to update storage settings- </p>- ) : (- <div />- )}- <div className="flex gap-2">- <Button- type="default"- htmlType="reset"- onClick={() => form.reset()}- disabled={isUpdating}- >- Cancel- </Button>- <Button- type="primary"- htmlType="submit"- loading={isUpdating}- disabled={!canUpdateStorageSettings || isUpdating}- >- Save- </Button>- </div>+ </div>+ {isFreeTier && (+ <div className="px-6 pb-6">+ <UpgradeToPro+ icon={<Clock size={14} className="text-foreground-muted" />}+ primaryText="Free Plan has a fixed upload file size limit of 50 MB."+ secondaryText="Upgrade to the Pro plan for a configurable upload file size limit of up to 50 GB."+ />+ </div>+ )}+ <div className="border-t border-overlay" />+ <div className="flex justify-between px-8 py-4">+ <div className="flex items-center justify-between w-full gap-2">+ {!canUpdateStorageSettings ? (+ <p className="text-sm text-foreground-light">+ You need additional permissions to update storage settings+ </p>+ ) : (+ <div />+ )}+ <div className="flex gap-2">+ <Button+ type="default"+ htmlType="reset"+ onClick={() => form.reset()}+ disabled={!canUpdateStorageSettings || isUpdating}+ >+ Cancel+ </Button>+ <Button+ type="primary"+ htmlType="submit"+ loading={isUpdating}+ disabled={!canUpdateStorageSettings || isUpdating}+ >+ Save+ </Button></div></div></div>- </form>- )}- </Form_Shadcn_>- </div>+ </div>+ </form>+ )}+ </Form_Shadcn_>)}diff --git a/apps/studio/components/ui/AlertError.tsx b/apps/studio/components/ui/AlertError.tsxindex 40af7218b51..877a3d9970b 100644--- a/apps/studio/components/ui/AlertError.tsx+++ b/apps/studio/components/ui/AlertError.tsx@@ -31,8 +31,8 @@ const AlertError = ({ projectRef, subject, error, className }: AlertErrorProps)<AlertTitle_Shadcn_>{subject}</AlertTitle_Shadcn_><AlertDescription_Shadcn_ className="flex flex-col gap-3 break-words"><div>- {error?.message && <p>Error: {formattedErrorMessage}</p>}- <p>+ {error?.message && <p className="text-left">Error: {formattedErrorMessage}</p>}+ <p className="text-left">Try refreshing your browser, but if the issue persists, please reach out to us viasupport.</p>diff --git a/apps/studio/components/ui/ButtonTooltip.tsx b/apps/studio/components/ui/ButtonTooltip.tsxnew file mode 100644index 00000000000..c2e7a7e5a31--- /dev/null+++ b/apps/studio/components/ui/ButtonTooltip.tsx@@ -0,0 +1,30 @@+import { ComponentProps, ComponentPropsWithoutRef, ElementRef, forwardRef } from 'react'+import { Button, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_, cn } from 'ui'++export const ButtonTooltip = forwardRef<+ ElementRef<typeof Button>,+ ComponentPropsWithoutRef<typeof Button> & {+ tooltip: {+ content: ComponentProps<typeof TooltipContent_Shadcn_> & {+ text?: string+ }+ }+ }+>(({ ...props }, ref) => {+ return (+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button ref={ref} {...props} className={cn(props.className, 'pointer-events-auto')}>+ {props.children}+ </Button>+ </TooltipTrigger_Shadcn_>+ {props.disabled && props.tooltip.content.text !== undefined && (+ <TooltipContent_Shadcn_ {...props.tooltip.content}>+ {props.tooltip.content.text}+ </TooltipContent_Shadcn_>+ )}+ </Tooltip_Shadcn_>+ )+})++ButtonTooltip.displayName = 'ButtonTooltip'diff --git a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsxindex 566f135772b..dcbfbcbadc7 100644--- a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx+++ b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx@@ -1,6 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'-import { Button, IconAlertCircle, IconBookOpen, IconLoader, Input } from 'ui'+import { Button, Input } from 'ui'import { useParams } from 'common/hooks'import Panel from 'components/ui/Panel'@@ -8,6 +8,7 @@ import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updatingimport { useProjectSettingsQuery } from 'data/config/project-settings-query'import { useCheckPermissions } from 'hooks'import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'+import { AlertCircle, BookOpen, Loader2 } from 'lucide-react'const DisplayApiSettings = () => {const { ref: projectRef } = useParams()@@ -47,7 +48,7 @@ const DisplayApiSettings = () => {You can use the keys below in the Supabase client libraries.<br /><a href="https://supabase.com/docs#client-libraries" target="_blank" rel="noreferrer">- <Button icon={<IconBookOpen />} type="default" className="mt-4">+ <Button icon={<BookOpen />} type="default" className="mt-4">Client Docs</Button></a>@@ -57,14 +58,14 @@ const DisplayApiSettings = () => {>{isProjectSettingsError || isJwtSecretUpdateStatusError ? (<div className="flex items-center justify-center py-8 space-x-2">- <IconAlertCircle size={16} strokeWidth={1.5} />+ <AlertCircle size={16} strokeWidth={1.5} /><p className="text-sm text-foreground-light">{isProjectSettingsError ? 'Failed to retrieve API keys' : 'Failed to update JWT secret'}</p></div>) : isApiKeysEmpty || isProjectSettingsLoading || isJwtSecretUpdateStatusLoading ? (<div className="flex items-center justify-center py-8 space-x-2">- <IconLoader className="animate-spin" size={16} strokeWidth={1.5} />+ <Loader2 className="animate-spin" size={16} strokeWidth={1.5} /><p className="text-sm text-foreground-light">{isProjectSettingsLoading || isApiKeysEmpty? 'Retrieving API keys'@@ -72,7 +73,7 @@ const DisplayApiSettings = () => {</p></div>) : (- apiKeys.map((x: any, i: number) => (+ apiKeys.map((x, i: number) => (<Panel.Contentkey={x.api_key}className={@@ -88,7 +89,7 @@ const DisplayApiSettings = () => {// @ts-ignorelabel={<>- {x.tags?.split(',').map((x: any, i: number) => (+ {x.tags?.split(',').map((x, i: number) => (<code key={`${x}${i}`} className="text-xs text-code">{x}</code>@@ -110,7 +111,7 @@ const DisplayApiSettings = () => {? 'JWT secret update failed, new API key may have issues': jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating? 'Updating JWT secret...'- : x.api_key+ : x?.api_key ?? 'You need additional permissions to view API keys'}onChange={() => {}}descriptionText={diff --git a/apps/studio/components/ui/SchemaSelector.tsx b/apps/studio/components/ui/SchemaSelector.tsxindex d0ea91d41fd..c69ab9993bb 100644--- a/apps/studio/components/ui/SchemaSelector.tsx+++ b/apps/studio/components/ui/SchemaSelector.tsx@@ -20,6 +20,8 @@ import {Popover_Shadcn_,ScrollArea,} from 'ui'+import { useCheckPermissions } from 'hooks'+import { PermissionAction } from '@supabase/shared-types/out/constants'interface SchemaSelectorProps {className?: string@@ -45,6 +47,7 @@ const SchemaSelector = ({onSelectCreateSchema,}: SchemaSelectorProps) => {const [open, setOpen] = useState(false)+ const canCreateSchemas = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'schemas')const { project } = useProjectContext()const {@@ -152,7 +155,7 @@ const SchemaSelector = ({))}</ScrollArea></CommandGroup_Shadcn_>- {onSelectCreateSchema !== undefined && (+ {onSelectCreateSchema !== undefined && canCreateSchemas && (<><CommandSeparator_Shadcn_ /><CommandGroup_Shadcn_>diff --git a/apps/studio/components/ui/UpgradeToPro.tsx b/apps/studio/components/ui/UpgradeToPro.tsxindex e8d004d315d..34e4f784aa3 100644--- a/apps/studio/components/ui/UpgradeToPro.tsx+++ b/apps/studio/components/ui/UpgradeToPro.tsx@@ -1,11 +1,11 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { PermissionAction } from '@supabase/shared-types/out/constants'import Link from 'next/link'import { ReactNode } from 'react'-import { Button } from 'ui'-import { useCheckPermissions, useFlag, useSelectedOrganization, useSelectedProject } from 'hooks'import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { useCheckPermissions, useFlag, useSelectedOrganization, useSelectedProject } from 'hooks'+import { Button, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_, cn } from 'ui'+import { ButtonTooltip } from './ButtonTooltip'interface UpgradeToProProps {icon?: ReactNode@@ -37,67 +37,54 @@ const UpgradeToPro = ({return (<div- className={[+ className={cn('block w-full rounded border border-opacity-20 py-4 px-6',- 'border-overlay bg-surface-200',- ].join(' ')}+ 'border-overlay bg-surface-200'+ )}>- <div className="flex space-x-3">+ <div className="flex gap-x-3">{icon && <div className="mt-1">{icon}</div>}- <div className="flex w-full items-center justify-between space-x-32">+ <div className="flex w-full items-center justify-between gap-x-32"><div className="space-y-1"><p className="text-sm">{primaryText}</p><div><p className="text-sm text-foreground-light">{secondaryText}</p></div></div>- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <Button- type="primary"- disabled={!canUpdateSubscription || projectUpdateDisabled || disabled}- asChild+ {!canUpdateSubscription || projectUpdateDisabled ? (+ <ButtonTooltip+ disabled+ type="primary"+ tooltip={{+ content: {+ side: 'bottom',+ text: projectUpdateDisabled+ ? 'Subscription changes are currently disabled, our engineers are working on a fix'+ : !canUpdateSubscription+ ? 'You need additional permissions to amend subscriptions'+ : undefined,+ },+ }}+ >+ Reset database password+ </ButtonTooltip>+ ) : (+ <Button+ asChild+ type="primary"+ disabled={!canUpdateSubscription || projectUpdateDisabled || disabled}+ >+ <Link+ href={+ plan === 'free'+ ? `/org/${organization?.slug ?? '_'}/billing?panel=subscriptionPlan`+ : `/project/${project?.ref ?? '_'}/settings/addons?panel=${addon}`+ }>- <Link- href={- plan === 'free'- ? `/org/${organization?.slug ?? '_'}/billing?panel=subscriptionPlan`- : `/project/${project?.ref ?? '_'}/settings/addons?panel=${addon}`- }- >- {buttonText || (plan === 'free' ? 'Upgrade to Pro' : 'Enable Addon')}- </Link>- </Button>- </Tooltip.Trigger>- {!canUpdateSubscription ||- (projectUpdateDisabled && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'border border-background text-center', //border- 'rounded bg-alternative py-1 px-2 leading-none shadow', // background- ].join(' ')}- >- <span className="text-xs text-foreground">- {projectUpdateDisabled ? (- <>- Subscription changes are currently disabled.- <br />- Our engineers are working on a fix.- </>- ) : !canUpdateSubscription ? (- 'You need additional permissions to amend subscriptions'- ) : (- ''- )}- </span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- ))}- </Tooltip.Root>+ {buttonText || (plan === 'free' ? 'Upgrade to Pro' : 'Enable add on')}+ </Link>+ </Button>+ )}</div></div></div>diff --git a/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.ts b/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.tsindex cde2f27d8ec..5e3a3207361 100644--- a/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.ts+++ b/apps/studio/data/analytics/warehouse-access-tokens-create-mutation.ts@@ -12,7 +12,7 @@ async function createWarehouseAccessToken({ref,description,}: WarehouseAccessTokenCreateVariables) {- const { data, error } = await post(`/platform/projects/{ref}/analytics/warehouse/access-tokens`, {+ const { data, error } = await post(`/v1/projects/{ref}/analytics/warehouse/access-tokens`, {params: {path: { ref },},diff --git a/apps/studio/data/analytics/warehouse-access-tokens-delete-mutation.ts b/apps/studio/data/analytics/warehouse-access-tokens-delete-mutation.tsindex 2d931a80037..8aa34940276 100644--- a/apps/studio/data/analytics/warehouse-access-tokens-delete-mutation.ts+++ b/apps/studio/data/analytics/warehouse-access-tokens-delete-mutation.ts@@ -11,7 +11,7 @@ export type DeleteAccessTokenArgs = {export async function deleteWarehouseAccessToken({ projectRef, token }: DeleteAccessTokenArgs) {const { data, error } = await del(- '/platform/projects/{ref}/analytics/warehouse/access-tokens/{token}',+ '/v1/projects/{ref}/analytics/warehouse/access-tokens/{token}',{params: { path: { ref: projectRef, token } } as any,}diff --git a/apps/studio/data/analytics/warehouse-access-tokens-query.ts b/apps/studio/data/analytics/warehouse-access-tokens-query.tsindex 5a8a7e877c2..10866103969 100644--- a/apps/studio/data/analytics/warehouse-access-tokens-query.ts+++ b/apps/studio/data/analytics/warehouse-access-tokens-query.ts@@ -15,7 +15,7 @@ export async function getWarehouseAccessTokens(throw new Error('projectRef is required')}- const response = await get(`/platform/projects/{ref}/analytics/warehouse/access-tokens`, {+ const response = await get(`/v1/projects/{ref}/analytics/warehouse/access-tokens`, {params: { path: { ref: projectRef } },signal,})diff --git a/apps/studio/data/analytics/warehouse-collections-create-mutation.ts b/apps/studio/data/analytics/warehouse-collections-create-mutation.tsindex c1cefea73ca..8b14d2c8217 100644--- a/apps/studio/data/analytics/warehouse-collections-create-mutation.ts+++ b/apps/studio/data/analytics/warehouse-collections-create-mutation.ts@@ -10,7 +10,7 @@ export type CreateCollectionArgs = {}export async function createCollection({ projectRef, name }: CreateCollectionArgs) {- const { data, error } = await post('/platform/projects/{ref}/analytics/warehouse/collections', {+ const { data, error } = await post('/v1/projects/{ref}/analytics/warehouse/collections', {params: { path: { ref: projectRef } },body: { name },} as any)diff --git a/apps/studio/data/analytics/warehouse-collections-delete-mutation.ts b/apps/studio/data/analytics/warehouse-collections-delete-mutation.tsindex 1420074960a..168b38aeb4b 100644--- a/apps/studio/data/analytics/warehouse-collections-delete-mutation.ts+++ b/apps/studio/data/analytics/warehouse-collections-delete-mutation.ts@@ -11,12 +11,9 @@ export type DeleteCollectionVariables = {}export async function deleteCollection({ projectRef, collectionToken }: DeleteCollectionVariables) {- const { data, error } = await del(- '/platform/projects/{ref}/analytics/warehouse/collections/{token}',- {- params: { path: { ref: projectRef, token: collectionToken } } as any,- }- )+ const { data, error } = await del('/v1/projects/{ref}/analytics/warehouse/collections/{token}', {+ params: { path: { ref: projectRef, token: collectionToken } } as any,+ })if (error) handleError(error)return datadiff --git a/apps/studio/data/analytics/warehouse-collections-query.ts b/apps/studio/data/analytics/warehouse-collections-query.tsindex 2e963035eb2..282a74e14e5 100644--- a/apps/studio/data/analytics/warehouse-collections-query.ts+++ b/apps/studio/data/analytics/warehouse-collections-query.ts@@ -14,7 +14,7 @@ export async function getWarehouseCollections(throw new Error('projectRef is required')}- const { data, error } = await get(`/platform/projects/{ref}/analytics/warehouse/collections`, {+ const { data, error } = await get(`/v1/projects/{ref}/analytics/warehouse/collections`, {params: { path: { ref: projectRef } },signal,})diff --git a/apps/studio/data/analytics/warehouse-collections-update-mutation.ts b/apps/studio/data/analytics/warehouse-collections-update-mutation.tsindex 8c85f85e162..adf882c0c87 100644--- a/apps/studio/data/analytics/warehouse-collections-update-mutation.ts+++ b/apps/studio/data/analytics/warehouse-collections-update-mutation.ts@@ -20,7 +20,7 @@ export async function updateCollection(payload: UpdateCollectionPayload) {const { data, error } = await patch(- '/platform/projects/{ref}/analytics/warehouse/collections/{token}',+ '/v1/projects/{ref}/analytics/warehouse/collections/{token}',{params: { path: { ref: projectRef, token: collectionToken } },body: payload,diff --git a/apps/studio/data/analytics/warehouse-query.ts b/apps/studio/data/analytics/warehouse-query.tsindex 54c34a18414..1223a865d67 100644--- a/apps/studio/data/analytics/warehouse-query.ts+++ b/apps/studio/data/analytics/warehouse-query.ts@@ -16,7 +16,7 @@ export async function getWarehouseQuery(throw new Error('SQL must be provided')}- const { data, error } = await get(`/platform/projects/{ref}/analytics/warehouse/query`, {+ const { data, error } = await get(`/v1/projects/{ref}/analytics/warehouse/query`, {params: { path: { ref: ref }, query: { bq_sql: sql } },signal,} as any)diff --git a/apps/studio/data/analytics/warehouse-tenant-query.ts b/apps/studio/data/analytics/warehouse-tenant-query.tsindex 3a66c7889de..57fb3eebc52 100644--- a/apps/studio/data/analytics/warehouse-tenant-query.ts+++ b/apps/studio/data/analytics/warehouse-tenant-query.ts@@ -17,7 +17,7 @@ export async function getWarehouseTenant(throw new Error('projectRef is required')}- const { data, error } = await get(`/platform/projects/{ref}/analytics/warehouse/tenant`, {+ const { data, error } = await get(`/v1/projects/{ref}/analytics/warehouse/tenant`, {params: { path: { ref: projectRef } },signal,})diff --git a/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts b/apps/studio/data/api-authorization/api-authorization-approve-mutation.tsindex 8ee802a666f..c8f027bef98 100644--- a/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts+++ b/apps/studio/data/api-authorization/api-authorization-approve-mutation.ts@@ -1,32 +1,31 @@import { useMutation, UseMutationOptions } from '@tanstack/react-query'import toast from 'react-hot-toast'-import { post } from 'lib/common/fetch'-import { API_ADMIN_URL } from 'lib/constants'+import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'export type ApiAuthorizationApproveVariables = {id: string- organization_id: string+ slug: string}export type ApiAuthorizationApproveResponse = {url: string}-export async function approveApiAuthorization({- id,- organization_id,-}: ApiAuthorizationApproveVariables) {+export async function approveApiAuthorization({ id, slug }: ApiAuthorizationApproveVariables) {if (!id) throw new Error('Authorization ID is required')- if (!organization_id) throw new Error('Organization slug is required')+ if (!slug) throw new Error('Organization slug is required')- const response = await post(- `${API_ADMIN_URL}/oauth/authorizations/${id}?skip_browser_redirect=true`,- { organization_id }- )- if (response.error) throw response.error- return response as ApiAuthorizationApproveResponse+ const { data, error } = await post('/platform/organizations/{slug}/oauth/authorizations/{id}', {+ // @ts-ignore [Joshen] Endpoint doesnt need slug in the path params, but the endpoint path requires slug+ // it's a little weird, will need API to decide if they wanna shift this route outside of the {slug} endpoint+ params: { path: { slug, id }, query: { skip_browser_redirect: true } },+ body: { organization_id: slug },+ })++ if (error) handleError(error)+ return data as unknown as ApiAuthorizationApproveResponse}type ApiAuthorizationApproveData = Awaited<ReturnType<typeof approveApiAuthorization>>diff --git a/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts b/apps/studio/data/api-authorization/api-authorization-decline-mutation.tsindex 5a55574d679..d90744f4c29 100644--- a/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts+++ b/apps/studio/data/api-authorization/api-authorization-decline-mutation.ts@@ -1,24 +1,29 @@import { useMutation, UseMutationOptions } from '@tanstack/react-query'import toast from 'react-hot-toast'-import { delete_ } from 'lib/common/fetch'-import { API_ADMIN_URL } from 'lib/constants'+import { del, handleError } from 'data/fetchers'import type { ResponseError } from 'types'export type ApiAuthorizationDeclineVariables = {id: string+ slug: string}export type ApiAuthorizationDeclineResponse = {id: string}-export async function declineApiAuthorization({ id }: ApiAuthorizationDeclineVariables) {+export async function declineApiAuthorization({ id, slug }: ApiAuthorizationDeclineVariables) {if (!id) throw new Error('Authorization ID is required')- const response = await delete_(`${API_ADMIN_URL}/oauth/authorizations/${id}`, {})- if (response.error) throw response.error- return response as ApiAuthorizationDeclineResponse+ const { data, error } = await del('/platform/organizations/{slug}/oauth/authorizations/{id}', {+ // @ts-ignore [Joshen] Endpoint doesnt need slug in the path params, but the endpoint path requires slug+ // it's a little weird, will need API to decide if they wanna shift this route outside of the {slug} endpoint+ params: { path: { slug, id } },+ })++ if (error) handleError(error)+ return data as ApiAuthorizationDeclineResponse}type ApiAuthorizationDeclineData = Awaited<ReturnType<typeof declineApiAuthorization>>diff --git a/apps/studio/data/api-authorization/api-authorization-query.ts b/apps/studio/data/api-authorization/api-authorization-query.tsindex 425cb98deb7..fe72e9343e8 100644--- a/apps/studio/data/api-authorization/api-authorization-query.ts+++ b/apps/studio/data/api-authorization/api-authorization-query.ts@@ -1,11 +1,13 @@import type { OAuthScope } from '@supabase/shared-types/out/constants'import { useQuery, UseQueryOptions } from '@tanstack/react-query'-import { get } from 'lib/common/fetch'-import { API_ADMIN_URL } from 'lib/constants'++import { get, handleError } from 'data/fetchers'+import { API_URL } from 'lib/constants'import { resourceKeys } from './keys'export type ApiAuthorizationVariables = {id?: string+ slug?: string}export type ApiAuthorizationResponse = {@@ -20,26 +22,32 @@ export type ApiAuthorizationResponse = {}export async function getApiAuthorizationDetails(- { id }: ApiAuthorizationVariables,+ { id, slug }: ApiAuthorizationVariables,signal?: AbortSignal) {if (!id) throw new Error('Authorization ID is required')- const response = await get(`${API_ADMIN_URL}/oauth/authorizations/${id}`, { signal })- if (response.error) throw response.error- return response as ApiAuthorizationResponse+ const { data, error } = await get('/platform/organizations/{slug}/oauth/authorizations/{id}', {+ // @ts-ignore [Joshen] Endpoint doesnt need slug in the path params, but the endpoint path requires slug+ // it's a little weird, will need API to decide if they wanna shift this route outside of the {slug} endpoint+ params: { path: { slug, id } },+ signal,+ })++ if (error) handleError(error)+ return data as ApiAuthorizationResponse}export type ResourceData = Awaited<ReturnType<typeof getApiAuthorizationDetails>>export type ResourceError = { errorEventId: string; message: string }export const useApiAuthorizationQuery = <TData = ResourceData>(- { id }: ApiAuthorizationVariables,+ { id, slug }: ApiAuthorizationVariables,{ enabled = true, ...options }: UseQueryOptions<ResourceData, ResourceError, TData> = {}) =>useQuery<ResourceData, ResourceError, TData>(resourceKeys.resource(id),- ({ signal }) => getApiAuthorizationDetails({ id }, signal),+ ({ signal }) => getApiAuthorizationDetails({ id, slug }, signal),{enabled: enabled && typeof id !== 'undefined',...options,diff --git a/apps/studio/data/organization-members/keys.ts b/apps/studio/data/organization-members/keys.tsnew file mode 100644index 00000000000..de11852f94a--- /dev/null+++ b/apps/studio/data/organization-members/keys.ts@@ -0,0 +1,8 @@+export const organizationKeys = {+ rolesV2: (slug: string | undefined) => ['organization-members', slug, 'roles-v2'] as const,+ invitations: (slug: string | undefined) => ['organization-members', slug, 'invitations'] as const,+ invitation: (slug: string | undefined, token: string | undefined) =>+ ['organization-members', slug, 'invitations', token] as const,+ token: (slug: string | undefined, token: string | undefined) =>+ ['organization-members', slug, 'token', token] as const,+}diff --git a/apps/studio/data/organization-members/organization-invitation-accept-mutation.ts b/apps/studio/data/organization-members/organization-invitation-accept-mutation.tsnew file mode 100644index 00000000000..600858ca3d5--- /dev/null+++ b/apps/studio/data/organization-members/organization-invitation-accept-mutation.ts@@ -0,0 +1,55 @@+import { useMutation, UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { handleError, post } from 'data/fetchers'+import type { ResponseError } from 'types'++export type OrganizationAcceptInvitationVariables = {+ slug: string+ token: string+}++export async function acceptOrganizationInvitation({+ slug,+ token,+}: OrganizationAcceptInvitationVariables) {+ const { data, error } = await post('/platform/organizations/{slug}/members/invitations/{token}', {+ params: { path: { slug, token } },+ })++ if (error) handleError(error)+ return data+}++type OrganizationMemberUpdateData = Awaited<ReturnType<typeof acceptOrganizationInvitation>>++export const useOrganizationAcceptInvitationMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ OrganizationMemberUpdateData,+ ResponseError,+ OrganizationAcceptInvitationVariables+ >,+ 'mutationFn'+> = {}) => {+ return useMutation<+ OrganizationMemberUpdateData,+ ResponseError,+ OrganizationAcceptInvitationVariables+ >((vars) => acceptOrganizationInvitation(vars), {+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to accept invitation: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organization-members/organization-invitation-create-mutation.ts b/apps/studio/data/organization-members/organization-invitation-create-mutation.tsnew file mode 100644index 00000000000..f08483e0d90--- /dev/null+++ b/apps/studio/data/organization-members/organization-invitation-create-mutation.ts@@ -0,0 +1,75 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { components } from 'api-types'+import { handleError, post } from 'data/fetchers'+import { organizationKeys as organizationKeysV1 } from 'data/organizations/keys'+import type { ResponseError } from 'types'+import { organizationKeys } from './keys'++export type OrganizationCreateInvitationVariables = {+ slug: string+ email: string+ roleId: number+ projects?: string[]+}++export async function createOrganizationInvitation({+ slug,+ email,+ roleId,+ projects,+}: OrganizationCreateInvitationVariables) {+ const payload: components['schemas']['CreateInvitationBody'] = { email, role_id: roleId }+ if (projects !== undefined) payload.role_scoped_projects = projects++ const { data, error } = await post('/platform/organizations/{slug}/members/invitations', {+ params: { path: { slug } },+ body: payload,+ })++ if (error) handleError(error)+ return data+}++type OrganizationMemberUpdateData = Awaited<ReturnType<typeof createOrganizationInvitation>>++export const useOrganizationCreateInvitationMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ OrganizationMemberUpdateData,+ ResponseError,+ OrganizationCreateInvitationVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ OrganizationMemberUpdateData,+ ResponseError,+ OrganizationCreateInvitationVariables+ >((vars) => createOrganizationInvitation(vars), {+ async onSuccess(data, variables, context) {+ const { slug } = variables++ await Promise.all([+ queryClient.invalidateQueries(organizationKeys.rolesV2(slug)),+ queryClient.invalidateQueries(organizationKeysV1.members(slug)),+ ])++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update member role: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organization-members/organization-invitation-delete-mutation.ts b/apps/studio/data/organization-members/organization-invitation-delete-mutation.tsnew file mode 100644index 00000000000..242362ca065--- /dev/null+++ b/apps/studio/data/organization-members/organization-invitation-delete-mutation.ts@@ -0,0 +1,69 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { del, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { organizationKeys as organizationKeysV1 } from '../organizations/keys'+import { organizationKeys } from './keys'++export type OrganizationDeleteInvitationVariables = {+ slug: string+ id: number+ skipInvalidation?: boolean+}++export async function deleteOrganizationInvitation({+ slug,+ id,+}: OrganizationDeleteInvitationVariables) {+ const { error } = await del('/platform/organizations/{slug}/members/invitations/{id}', {+ params: { path: { slug, id } },+ })++ if (error) handleError(error)+ return true+}++type OrganizationDeleteInvitationData = Awaited<ReturnType<typeof deleteOrganizationInvitation>>++export const useOrganizationDeleteInvitationMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ OrganizationDeleteInvitationData,+ ResponseError,+ OrganizationDeleteInvitationVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ OrganizationDeleteInvitationData,+ ResponseError,+ OrganizationDeleteInvitationVariables+ >((vars) => deleteOrganizationInvitation(vars), {+ async onSuccess(data, variables, context) {+ const { slug, skipInvalidation } = variables++ if (!skipInvalidation) {+ await Promise.all([+ queryClient.invalidateQueries(organizationKeys.rolesV2(slug)),+ queryClient.invalidateQueries(organizationKeysV1.members(slug)),+ ])+ }++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to delete invitation: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organization-members/organization-invitation-token-query.ts b/apps/studio/data/organization-members/organization-invitation-token-query.tsnew file mode 100644index 00000000000..921c3d978b9--- /dev/null+++ b/apps/studio/data/organization-members/organization-invitation-token-query.ts@@ -0,0 +1,46 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import { get, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { organizationKeys } from './keys'+import { components } from 'api-types'++export type OrganizationInviteTokenVariables = { slug?: string; token?: string }++export type OrganizationInviteByToken = components['schemas']['InvitationByTokenResponse']++export async function getOrganizationInviteByToken(+ { slug, token }: OrganizationInviteTokenVariables,+ signal?: AbortSignal+) {+ if (!slug) throw new Error('slug is required')+ if (!token) throw new Error('token is required')++ const { data, error } = await get('/platform/organizations/{slug}/members/invitations/{token}', {+ params: { path: { slug, token } },+ signal,+ })++ if (error) handleError(error)+ return data+}++export type OrganizationInviteTokenData = Awaited<ReturnType<typeof getOrganizationInviteByToken>>+export type OrganizationInviteTokenError = ResponseError++export const useOrganizationInvitationTokenQuery = <TData = OrganizationInviteTokenData>(+ { slug, token }: OrganizationInviteTokenVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<OrganizationInviteTokenData, OrganizationInviteTokenError, TData> = {}+) => {+ return useQuery<OrganizationInviteTokenData, OrganizationInviteTokenError, TData>(+ organizationKeys.token(slug, token),+ ({ signal }) => getOrganizationInviteByToken({ slug, token }, signal),+ {+ enabled: enabled && typeof slug !== 'undefined' && typeof token !== 'undefined',+ ...options,+ }+ )+}diff --git a/apps/studio/data/organization-members/organization-member-role-assign-mutation.ts b/apps/studio/data/organization-members/organization-member-role-assign-mutation.tsnew file mode 100644index 00000000000..858471219f0--- /dev/null+++ b/apps/studio/data/organization-members/organization-member-role-assign-mutation.ts@@ -0,0 +1,79 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { organizationKeys } from './keys'+import { organizationKeys as organizationKeysV1 } from 'data/organizations/keys'+import type { ResponseError } from 'types'+import { handleError, patch } from 'data/fetchers'+import { components } from 'api-types'++export type OrganizationMemberAssignRoleVariables = {+ slug: string+ gotrueId: string+ roleId: number+ projects?: string[]+ skipInvalidation?: boolean+}++export async function assignOrganizationMemberRole({+ slug,+ gotrueId,+ roleId,+ projects,+}: OrganizationMemberAssignRoleVariables) {+ const payload: components['schemas']['AssignMemberRoleBodyV2'] = { role_id: roleId }+ if (projects !== undefined) payload.role_scoped_projects = projects++ const { data, error } = await patch('/platform/organizations/{slug}/members/{gotrue_id}', {+ params: { path: { slug, gotrue_id: gotrueId } },+ body: payload,+ headers: { Version: '2' },+ })++ if (error) handleError(error)+ return data+}++type OrganizationMemberAssignData = Awaited<ReturnType<typeof assignOrganizationMemberRole>>++export const useOrganizationMemberAssignRoleMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ OrganizationMemberAssignData,+ ResponseError,+ OrganizationMemberAssignRoleVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ OrganizationMemberAssignData,+ ResponseError,+ OrganizationMemberAssignRoleVariables+ >((vars) => assignOrganizationMemberRole(vars), {+ async onSuccess(data, variables, context) {+ const { slug, skipInvalidation } = variables++ if (!skipInvalidation) {+ await Promise.all([+ queryClient.invalidateQueries(organizationKeys.rolesV2(slug)),+ queryClient.invalidateQueries(organizationKeysV1.members(slug)),+ ])+ }++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update member role: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organization-members/organization-member-role-unassign-mutation.ts b/apps/studio/data/organization-members/organization-member-role-unassign-mutation.tsnew file mode 100644index 00000000000..cb281278d16--- /dev/null+++ b/apps/studio/data/organization-members/organization-member-role-unassign-mutation.ts@@ -0,0 +1,80 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { del, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { organizationKeys } from './keys'+import { organizationKeys as organizationKeysV1 } from 'data/organizations/keys'++export type OrganizationMemberUnassignRoleVariables = {+ slug: string+ gotrueId: string+ roleId: number+ skipInvalidation?: boolean+}++export async function unassignOrganizationMemberRole({+ slug,+ gotrueId,+ roleId,+}: OrganizationMemberUnassignRoleVariables) {+ const { data, error } = await del(+ '/platform/organizations/{slug}/members/{gotrue_id}/roles/{role_id}',+ {+ params: {+ path: {+ slug,+ gotrue_id: gotrueId,+ role_id: roleId.toString(),+ },+ },+ }+ )++ if (error) handleError(error)+ return data+}++type OrganizationMemberUnassignRoleData = Awaited<ReturnType<typeof unassignOrganizationMemberRole>>++export const useOrganizationMemberUnassignRoleMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ OrganizationMemberUnassignRoleData,+ ResponseError,+ OrganizationMemberUnassignRoleVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ OrganizationMemberUnassignRoleData,+ ResponseError,+ OrganizationMemberUnassignRoleVariables+ >((vars) => unassignOrganizationMemberRole(vars), {+ async onSuccess(data, variables, context) {+ const { slug, skipInvalidation } = variables++ if (!skipInvalidation) {+ await Promise.all([+ queryClient.invalidateQueries(organizationKeys.rolesV2(slug)),+ queryClient.invalidateQueries(organizationKeysV1.members(slug)),+ ])+ }++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to unassign member role: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organization-members/organization-member-role-update-mutation.ts b/apps/studio/data/organization-members/organization-member-role-update-mutation.tsnew file mode 100644index 00000000000..0b577c8961b--- /dev/null+++ b/apps/studio/data/organization-members/organization-member-role-update-mutation.ts@@ -0,0 +1,79 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'react-hot-toast'++import { handleError, put } from 'data/fetchers'+import { organizationKeys as organizationKeysV1 } from 'data/organizations/keys'+import type { ResponseError } from 'types'+import { organizationKeys } from './keys'++export type OrganizationMemberUpdateRoleVariables = {+ slug: string+ gotrueId: string+ roleId: number+ roleName: string+ projects: string[]+ skipInvalidation?: boolean+}++export async function assignOrganizationMemberRole({+ slug,+ gotrueId,+ roleId,+ roleName,+ projects,+}: OrganizationMemberUpdateRoleVariables) {+ const { data, error } = await put(+ '/platform/organizations/{slug}/members/{gotrue_id}/roles/{role_id}',+ {+ params: { path: { slug, gotrue_id: gotrueId, role_id: roleId.toString() } },+ body: { name: roleName, role_scoped_projects: projects },+ }+ )++ if (error) handleError(error)+ return data+}++type OrganizationMemberAssignData = Awaited<ReturnType<typeof assignOrganizationMemberRole>>++export const useOrganizationMemberUpdateRoleMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ OrganizationMemberAssignData,+ ResponseError,+ OrganizationMemberUpdateRoleVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ OrganizationMemberAssignData,+ ResponseError,+ OrganizationMemberUpdateRoleVariables+ >((vars) => assignOrganizationMemberRole(vars), {+ async onSuccess(data, variables, context) {+ const { slug, skipInvalidation } = variables++ if (!skipInvalidation) {+ await Promise.all([+ queryClient.invalidateQueries(organizationKeys.rolesV2(slug)),+ queryClient.invalidateQueries(organizationKeysV1.members(slug)),+ ])+ }++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update member role: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/organization-members/organization-roles-query.ts b/apps/studio/data/organization-members/organization-roles-query.tsnew file mode 100644index 00000000000..91225e6bfca--- /dev/null+++ b/apps/studio/data/organization-members/organization-roles-query.ts@@ -0,0 +1,45 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import type { components } from 'api-types'+import { get, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { organizationKeys } from './keys'++export type OrganizationRolesVariables = { slug?: string }+export type OrganizationRolesResponse = components['schemas']['OrganizationRoleResponseV2']+export type OrganizationRole = components['schemas']['OrganizationRoleV2']++export async function getOrganizationRoles(+ { slug }: OrganizationRolesVariables,+ signal?: AbortSignal+) {+ if (!slug) throw new Error('slug is required')++ const { data, error } = await get('/platform/organizations/{slug}/roles', {+ params: { path: { slug } },+ headers: { Version: '2' },+ signal,+ })++ if (error) handleError(error)+ return data+}++export type OrganizationRolesData = Awaited<ReturnType<typeof getOrganizationRoles>>+export type OrganizationRolesError = ResponseError++export const useOrganizationRolesV2Query = <TData = OrganizationRolesData>(+ { slug }: OrganizationRolesVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<OrganizationRolesData, OrganizationRolesError, TData> = {}+) =>+ useQuery<OrganizationRolesData, OrganizationRolesError, TData>(+ organizationKeys.rolesV2(slug),+ ({ signal }) => getOrganizationRoles({ slug }, signal),+ {+ enabled: enabled && typeof slug !== 'undefined',+ ...options,+ }+ )diff --git a/apps/studio/data/organizations/organization-customer-profile-query.ts b/apps/studio/data/organizations/organization-customer-profile-query.tsindex dcb1e2a0d46..5b1fc881631 100644--- a/apps/studio/data/organizations/organization-customer-profile-query.ts+++ b/apps/studio/data/organizations/organization-customer-profile-query.ts@@ -1,7 +1,10 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQuery, UseQueryOptions } from '@tanstack/react-query'+import { get, handleError } from 'data/fetchers'-import { organizationKeys } from './keys'+import { useCheckPermissions } from 'hooks'import type { ResponseError } from 'types'+import { organizationKeys } from './keys'export type OrganizationCustomerProfileVariables = {slug?: string@@ -37,12 +40,20 @@ export const useOrganizationCustomerProfileQuery = <TData = OrganizationCustomerenabled = true,...options}: UseQueryOptions<OrganizationCustomerProfileData, OrganizationCustomerProfileError, TData> = {}-) =>- useQuery<OrganizationCustomerProfileData, OrganizationCustomerProfileError, TData>(+) => {+ // [Joshen] Thinking it makes sense to add this check at the RQ level - prevent+ // unnecessary requests, although this behaviour still needs handling on the UI+ const canReadCustomerProfile = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.customer'+ )++ return useQuery<OrganizationCustomerProfileData, OrganizationCustomerProfileError, TData>(organizationKeys.customerProfile(slug),({ signal }) => getOrganizationCustomerProfile({ slug }, signal),{- enabled: enabled && typeof slug !== 'undefined',+ enabled: enabled && canReadCustomerProfile && typeof slug !== 'undefined',...options,})+}diff --git a/apps/studio/data/organizations/organization-join-decline-mutation.ts b/apps/studio/data/organizations/organization-join-decline-mutation.tsindex abe1c4748f7..d220a48c79a 100644--- a/apps/studio/data/organizations/organization-join-decline-mutation.ts+++ b/apps/studio/data/organizations/organization-join-decline-mutation.ts@@ -4,6 +4,8 @@ import { toast } from 'react-hot-toast'import { del, handleError } from 'data/fetchers'import type { ResponseError } from 'types'+// [Joshen] This is a duplicate of organization-member-invite-delete-mutation, to remove one of them+export type OrganizationJoinDeclineVariables = {slug: stringinvited_id: stringdiff --git a/apps/studio/data/organizations/organization-join-mutation.ts b/apps/studio/data/organizations/organization-join-mutation.tsindex 3755bdb9445..f680a90a3a3 100644--- a/apps/studio/data/organizations/organization-join-mutation.ts+++ b/apps/studio/data/organizations/organization-join-mutation.ts@@ -10,6 +10,8 @@ export type OrganizationJoinVariables = {token: string}+// [Joshen TODO] Should be deprecated now - double check before deleting+export async function joinOrganization({ slug, token }: OrganizationJoinVariables) {const { data, error } = await post('/platform/organizations/{slug}/members/join', {params: { path: { slug }, query: { token } },diff --git a/apps/studio/data/organizations/organization-join-token-validation-query.ts b/apps/studio/data/organizations/organization-join-token-validation-query.tsindex 1fe1f2d8b03..a80ba45b0b5 100644--- a/apps/studio/data/organizations/organization-join-token-validation-query.ts+++ b/apps/studio/data/organizations/organization-join-token-validation-query.ts@@ -11,6 +11,8 @@ export type OrganizationJoinTokenValidationVariables = {export type TokenInfo = components['schemas']['InviteResponse'] | undefined+// [Joshen TODO] Should be deprecated now - double check before deleting+export async function validateTokenInformation({ slug, token }: OrganizationJoinTokenValidationVariables,signal?: AbortSignaldiff --git a/apps/studio/data/organizations/organization-member-invite-create-mutation.ts b/apps/studio/data/organizations/organization-member-invite-create-mutation.tsindex 487c8b0ae44..16ddbf8d25c 100644--- a/apps/studio/data/organizations/organization-member-invite-create-mutation.ts+++ b/apps/studio/data/organizations/organization-member-invite-create-mutation.ts@@ -13,6 +13,8 @@ export type OrganizationMemberInviteCreateVariables = {roleId: number}+// [Joshen TODO] Should be deprecated now - double check before deleting+export async function createOrganizationMemberInvite({slug,invitedEmail,diff --git a/apps/studio/data/organizations/organization-member-invite-delete-mutation.ts b/apps/studio/data/organizations/organization-member-invite-delete-mutation.tsindex 41a640feb65..26694650c25 100644--- a/apps/studio/data/organizations/organization-member-invite-delete-mutation.ts+++ b/apps/studio/data/organizations/organization-member-invite-delete-mutation.ts@@ -1,8 +1,7 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'react-hot-toast'-import { delete_ } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { del, handleError } from 'data/fetchers'import type { ResponseError } from 'types'import { organizationKeys } from './keys'@@ -12,16 +11,17 @@ export type OrganizationMemberInviteDeleteVariables = {invalidateDetail?: boolean}+// [Joshen TODO] Should be deprecated now - double check before deleting+export async function deleteOrganizationMemberInvite({slug,invitedId,}: OrganizationMemberInviteDeleteVariables) {- const response = await delete_(- `${API_URL}/organizations/${slug}/members/invite?invited_id=${invitedId}`,- {}- )- if (response.error) throw response.error- return response+ const { data, error } = await del('/platform/organizations/{slug}/members/invite', {+ params: { path: { slug }, query: { invited_id: invitedId } },+ })+ if (error) handleError(error)+ return data}type OrganizationMemberInviteDeleteData = Awaited<ReturnType<typeof deleteOrganizationMemberInvite>>diff --git a/apps/studio/data/organizations/organization-members-query.ts b/apps/studio/data/organizations/organization-members-query.tsindex 90a7bf069f1..1ea24b2de9e 100644--- a/apps/studio/data/organizations/organization-members-query.ts+++ b/apps/studio/data/organizations/organization-members-query.ts@@ -23,7 +23,10 @@ export async function getOrganizationMembers(const [members, invites] = await Promise.all([get('/platform/organizations/{slug}/members', { params: { path: { slug } }, signal }),- get('/platform/organizations/{slug}/members/invite', { params: { path: { slug } }, signal }),+ get('/platform/organizations/{slug}/members/invitations', {+ params: { path: { slug } },+ signal,+ }),])const { data: orgMembers, error: orgMembersError } = members@@ -33,10 +36,10 @@ export async function getOrganizationMembers(if (orgInvitesError) handleError(orgInvitesError)// Remap invite data to look like existing members data- const invitedMembers = orgInvites.map((invite) => {+ const invitedMembers = orgInvites.invitations.map((invite) => {const member = {invited_at: invite.invited_at,- invited_id: invite.invited_id,+ invited_id: invite.id,mfa_enabled: false,username: invite.invited_email.slice(0, 1),primary_email: invite.invited_email,diff --git a/apps/studio/data/organizations/organization-roles-query.ts b/apps/studio/data/organizations/organization-roles-query.tsindex 517d6359386..1331c9c1b35 100644--- a/apps/studio/data/organizations/organization-roles-query.ts+++ b/apps/studio/data/organizations/organization-roles-query.ts@@ -1,6 +1,6 @@import { useQuery, UseQueryOptions } from '@tanstack/react-query'-import { get } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'++import { get, handleError } from 'data/fetchers'import type { ResponseError, Role } from 'types'import { organizationKeys } from './keys'@@ -16,18 +16,16 @@ export async function getOrganizationRoles({ slug }: OrganizationRolesVariables,signal?: AbortSignal) {- if (!slug) {- throw new Error('slug is required')- }+ if (!slug) throw new Error('slug is required')- const data = await get(`${API_URL}/organizations/${slug}/roles`, {+ const { data, error } = await get('/platform/organizations/{slug}/roles', {+ params: { path: { slug } },signal,})- if (data.error) {- throw data.error- }- return { roles: data } as OrganizationRolesResponse+ if (error) handleError(error)++ return { roles: data } as unknown as OrganizationRolesResponse}export type OrganizationRolesData = Awaited<ReturnType<typeof getOrganizationRoles>>diff --git a/apps/studio/data/profile/profile-update-mutation.ts b/apps/studio/data/profile/profile-update-mutation.tsindex eed2847c746..47e4412a749 100644--- a/apps/studio/data/profile/profile-update-mutation.ts+++ b/apps/studio/data/profile/profile-update-mutation.ts@@ -1,8 +1,7 @@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 { handleError, patch } from 'data/fetchers'import type { ResponseError } from 'types'import { profileKeys } from './keys'@@ -12,15 +11,12 @@ export type ProfileUpdateVariables = {}export async function updateProfile({ firstName, lastName }: ProfileUpdateVariables) {- const response = await patch(`${API_URL}/profile`, {- first_name: firstName,- last_name: lastName,+ const { data, error } = await patch('/platform/profile', {+ body: { first_name: firstName, last_name: lastName },})- if (response.error) {- throw response.error- }- return response+ if (error) handleError(error)+ return data}type ProfileUpdateData = Awaited<ReturnType<typeof updateProfile>>diff --git a/apps/studio/data/subscriptions/org-subscription-query.ts b/apps/studio/data/subscriptions/org-subscription-query.tsindex 5c1e0e60ec7..e68f0431e77 100644--- a/apps/studio/data/subscriptions/org-subscription-query.ts+++ b/apps/studio/data/subscriptions/org-subscription-query.ts@@ -1,7 +1,10 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import { useQuery, UseQueryOptions } from '@tanstack/react-query'+import { get, handleError } from 'data/fetchers'-import { subscriptionKeys } from './keys'+import { useCheckPermissions } from 'hooks'import type { ResponseError } from 'types'+import { subscriptionKeys } from './keys'export type OrgSubscriptionVariables = {orgSlug?: string@@ -31,12 +34,20 @@ export const useOrgSubscriptionQuery = <TData = OrgSubscriptionData>(enabled = true,...options}: UseQueryOptions<OrgSubscriptionData, OrgSubscriptionError, TData> = {}-) =>- useQuery<OrgSubscriptionData, OrgSubscriptionError, TData>(+) => {+ // [Joshen] Thinking it makes sense to add this check at the RQ level - prevent+ // unnecessary requests, although this behaviour still needs handling on the UI+ const canReadSubscriptions = useCheckPermissions(+ PermissionAction.BILLING_READ,+ 'stripe.subscriptions'+ )++ return useQuery<OrgSubscriptionData, OrgSubscriptionError, TData>(subscriptionKeys.orgSubscription(orgSlug),({ signal }) => getOrgSubscription({ orgSlug }, signal),{- enabled: enabled && typeof orgSlug !== 'undefined',+ enabled: enabled && canReadSubscriptions && typeof orgSlug !== 'undefined',...options,})+}diff --git a/apps/studio/hooks/misc/useCheckPermissions.ts b/apps/studio/hooks/misc/useCheckPermissions.tsindex b88983594e0..e52b24e5a55 100644--- a/apps/studio/hooks/misc/useCheckPermissions.ts+++ b/apps/studio/hooks/misc/useCheckPermissions.ts@@ -1,4 +1,4 @@-import { useIsLoggedIn } from 'common'+import { useIsLoggedIn, useParams } from 'common'import jsonLogic from 'json-logic-js'import { useOrganizationsQuery } from 'data/organizations/organizations-query'@@ -6,38 +6,79 @@ import { usePermissionsQuery } from 'data/permissions/permissions-query'import { IS_PLATFORM } from 'lib/constants'import type { Permission } from 'types'import { useSelectedOrganization } from './useSelectedOrganization'+import { useSelectedProject } from './useSelectedProject'+import { useProjectDetailQuery } from 'data/projects/project-detail-query'const toRegexpString = (actionOrResource: string) =>`^${actionOrResource.replace('.', '\\.').replace('%', '.*')}$`+function doPermissionConditionCheck(permissions: Permission[], data?: object) {+ const isRestricted = permissions+ .filter((permission) => permission.restrictive)+ .some(+ ({ condition }: { condition: jsonLogic.RulesLogic }) =>+ condition === null || jsonLogic.apply(condition, data)+ )+ if (isRestricted) return false++ return permissions+ .filter((permission) => !permission.restrictive)+ .some(+ ({ condition }: { condition: jsonLogic.RulesLogic }) =>+ condition === null || jsonLogic.apply(condition, data)+ )+}+export function doPermissionsCheck(permissions: Permission[] | undefined,action: string,resource: string,data?: object,- organizationId?: number+ organizationId?: number,+ projectId?: number) {if (!permissions || !Array.isArray(permissions)) {return false}- return permissions+ if (projectId) {+ const projectPermissions = permissions.filter(+ (permission) =>+ permission.organization_id === organizationId &&+ permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&+ permission.resources.some((res) => resource.match(toRegexpString(res))) &&+ permission.project_ids?.includes(projectId)+ )+ if (projectPermissions.length > 0) {+ return doPermissionConditionCheck(projectPermissions, { resource_name: resource, ...data })+ }+ }++ const orgPermissions = permissions+ // filter out org-level permission+ .filter((permission) => !permission.project_ids || permission.project_ids.length === 0).filter((permission) =>permission.organization_id === organizationId &&permission.actions.some((act) => (action ? action.match(toRegexpString(act)) : null)) &&permission.resources.some((res) => resource.match(toRegexpString(res))))- .some(- ({ condition }: { condition: jsonLogic.RulesLogic }) =>- condition === null || jsonLogic.apply(condition, { resource_name: resource, ...data })- )+ return doPermissionConditionCheck(orgPermissions, { resource_name: resource, ...data })}export function useGetPermissions(permissionsOverride?: Permission[],organizationIdOverride?: number,enabled = true+) {+ return useGetProjectPermissions(permissionsOverride, organizationIdOverride, undefined, enabled)+}++export function useGetProjectPermissions(+ permissionsOverride?: Permission[],+ organizationIdOverride?: number,+ projectIdOverride?: number,+ enabled = true) {const permissionsResult = usePermissionsQuery({enabled: permissionsOverride === undefined && enabled,@@ -54,9 +95,17 @@ export function useGetPermissions(organizationIdOverride === undefined ? organizationResult : { id: organizationIdOverride }const organizationId = organization?.id+ const projectResult = useSelectedProject({+ enabled: projectIdOverride === undefined && enabled,+ })++ const project = projectIdOverride === undefined ? projectResult : { id: projectIdOverride }+ const projectId = project?.id+return {permissions,organizationId,+ projectId,}}@@ -68,19 +117,37 @@ export function useCheckPermissions(// e.g If you want to use useCheckPermissions in a loop like organization settingsorganizationId?: number,permissions?: Permission[]+) {+ return useCheckProjectPermissions(action, resource, data, {+ organizationId,+ projectId: undefined,+ permissions,+ })+}++export function useCheckProjectPermissions(+ action: string,+ resource: string,+ data?: object,+ overrides?: {+ organizationId?: number+ projectId?: number+ permissions?: Permission[]+ }) {const isLoggedIn = useIsLoggedIn()+ const { organizationId, projectId, permissions } = overrides ?? {}- const { permissions: allPermissions, organizationId: orgId } = useGetPermissions(- permissions,- organizationId,- isLoggedIn- )+ const {+ permissions: allPermissions,+ organizationId: orgId,+ projectId: _projectId,+ } = useGetProjectPermissions(permissions, organizationId, projectId, isLoggedIn)if (!isLoggedIn) return falseif (!IS_PLATFORM) return true- return doPermissionsCheck(allPermissions, action, resource, data, orgId)+ return doPermissionsCheck(allPermissions, action, resource, data, orgId, _projectId)}export function usePermissionsLoaded() {@@ -88,7 +155,17 @@ export function usePermissionsLoaded() {const { isFetched: isPermissionsFetched } = usePermissionsQuery({ enabled: isLoggedIn })const { isFetched: isOrganizationsFetched } = useOrganizationsQuery({ enabled: isLoggedIn })+ const { ref } = useParams()+ const { isFetched: isProjectDetailFetched } = useProjectDetailQuery(+ { ref },+ { enabled: !!ref && isLoggedIn }+ )+if (!IS_PLATFORM) return true+ if (ref) {+ return isLoggedIn && isPermissionsFetched && isOrganizationsFetched && isProjectDetailFetched+ }+return isLoggedIn && isPermissionsFetched && isOrganizationsFetched}diff --git a/apps/studio/hooks/misc/useSelectedProject.ts b/apps/studio/hooks/misc/useSelectedProject.tsindex e6c2fe6e086..e90ec47fbb6 100644--- a/apps/studio/hooks/misc/useSelectedProject.ts+++ b/apps/studio/hooks/misc/useSelectedProject.ts@@ -3,9 +3,9 @@ import { useProjectDetailQuery } from 'data/projects/project-detail-query'import { useProjectsQuery } from 'data/projects/projects-query'import { useMemo } from 'react'-export function useSelectedProject() {+export function useSelectedProject({ enabled = true } = {}) {const { ref } = useParams()- const { data } = useProjectDetailQuery({ ref })+ const { data } = useProjectDetailQuery({ ref }, { enabled })return useMemo(() => data && { ...data, parentRef: data?.parent_project_ref ?? data?.ref },diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 760a09a845f..88699e7d727 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -39,7 +39,7 @@"@supabase/auth-helpers-react": "^0.4.2","@supabase/pg-meta": "*","@supabase/realtime-js-next": "npm:@supabase/[email protected]",- "@supabase/shared-types": "0.1.65",+ "@supabase/shared-types": "0.1.70","@supabase/supabase-js": "^2.41.1","@tanstack/react-query": "4.35.7","@tanstack/react-query-devtools": "4.35.7",@@ -73,7 +73,6 @@"next-themes": "^0.3.0","openai": "^4.20.1","openapi-fetch": "^0.6.2",- "p-queue": "^6.6.2","papaparse": "^5.3.1","path-to-regexp": "^6.2.0","pg-minify": "^1.6.3",diff --git a/apps/studio/pages/authorize.tsx b/apps/studio/pages/authorize.tsxindex 0f6573987ef..8531c7426b1 100644--- a/apps/studio/pages/authorize.tsx+++ b/apps/studio/pages/authorize.tsx@@ -22,10 +22,15 @@ import type { NextPageWithLayout } from 'types'const APIAuthorizationPage: NextPageWithLayout = () => {const router = useRouter()const { auth_id } = useParams()- const [selectedOrg, setSelectedOrg] = useState<string>()+ const [selectedOrgSlug, setSelectedOrgSlug] = useState<string>()const { data: organizations, isLoading: isLoadingOrganizations } = useOrganizationsQuery()- const { data: requester, isLoading, isError, error } = useApiAuthorizationQuery({ id: auth_id })+ const {+ data: requester,+ isLoading,+ isError,+ error,+ } = useApiAuthorizationQuery({ id: auth_id, slug: selectedOrgSlug })const isApproved = (requester?.approved_at ?? null) !== nullconst isExpired = dayjs().isAfter(dayjs(requester?.expires_at))@@ -44,7 +49,7 @@ const APIAuthorizationPage: NextPageWithLayout = () => {useEffect(() => {if (!isLoadingOrganizations) {- setSelectedOrg(organizations?.[0].slug ?? undefined)+ setSelectedOrgSlug(organizations?.[0].slug ?? undefined)}}, [isLoadingOrganizations])@@ -52,18 +57,22 @@ const APIAuthorizationPage: NextPageWithLayout = () => {if (!auth_id) {return toast.error('Unable to approve request: auth_id is missing ')}- if (!selectedOrg) {+ if (!selectedOrgSlug) {return toast.error('Unable to approve request: No organization selected')}- approveRequest({ id: auth_id, organization_id: selectedOrg })+ approveRequest({ id: auth_id, slug: selectedOrgSlug })}const onDeclineRequest = async () => {if (!auth_id) {return toast.error('Unable to decline request: auth_id is missing ')}- declineRequest({ id: auth_id })+ if (!selectedOrgSlug) {+ return toast.error('Unable to decline request: No organization selected')+ }++ declineRequest({ id: auth_id, slug: selectedOrgSlug })}if (isLoading) {@@ -174,9 +183,9 @@ const APIAuthorizationPage: NextPageWithLayout = () => {) : (<Listboxlabel="Select an organization to grant API access to"- value={selectedOrg}+ value={selectedOrgSlug}disabled={isExpired}- onChange={setSelectedOrg}+ onChange={setSelectedOrgSlug}>{(organizations ?? []).map((organization) => (<Listbox.Optiondiff --git a/apps/studio/pages/join.tsx b/apps/studio/pages/join.tsxnew file mode 100644index 00000000000..58f63aa217c--- /dev/null+++ b/apps/studio/pages/join.tsx@@ -0,0 +1,39 @@+import Link from 'next/link'+import { useRouter } from 'next/router'++import { OrganizationInvite } from 'components/interfaces/OrganizationInvite/OrganizationInvite'+import { NextPageWithLayout } from 'types'+import { cn } from 'ui'++const JoinOrganizationPage: NextPageWithLayout = () => {+ const router = useRouter()++ return (+ <div+ className={cn(+ 'flex h-full min-h-screen bg-studio',+ 'w-full flex-col place-items-center',+ 'items-center justify-center gap-8 px-5'+ )}+ >+ <Link href="/projects" className="flex items-center justify-center gap-4">+ <img+ src={`${router.basePath}/img/supabase-logo.svg`}+ alt="Supabase"+ className="block h-[24px] cursor-pointer rounded"+ />+ </Link>+ <div+ className={cn(+ 'mx-auto overflow-hidden rounded-md border',+ 'border-muted bg-alternative text-center shadow',+ 'md:w-[400px]'+ )}+ >+ <OrganizationInvite />+ </div>+ </div>+ )+}++export default JoinOrganizationPagediff --git a/apps/studio/pages/join/index.tsx b/apps/studio/pages/join/index.tsxdeleted file mode 100644index cd767fffef3..00000000000--- a/apps/studio/pages/join/index.tsx+++ /dev/null@@ -1,272 +0,0 @@-import { useParams } from 'common'-import Link from 'next/link'-import { useRouter } from 'next/router'-import { useEffect, useState } from 'react'-import toast from 'react-hot-toast'-import { Button, IconCheckSquare, Loading } from 'ui'--import { useOrganizationJoinDeclineMutation } from 'data/organizations/organization-join-decline-mutation'-import { useOrganizationJoinMutation } from 'data/organizations/organization-join-mutation'-import {- TokenInfo,- validateTokenInformation,-} from 'data/organizations/organization-join-token-validation-query'-import { useSignOut } from 'lib/auth'-import { useProfile } from 'lib/profile'--const JoinOrganizationPage = () => {- const router = useRouter()- const { slug, token, name } = useParams()- const { profile } = useProfile()- const signOut = useSignOut()-- const [isSubmitting, setIsSubmitting] = useState(false)- const [error, setError] = useState<any>()- const [tokenValidationInfo, setTokenValidationInfo] = useState<TokenInfo>(undefined)- const [tokenInfoLoaded, setTokenInfoLoaded] = useState(false)- const {- token_does_not_exist,- sso_mismatch,- email_match,- expired_token,- organization_name,- invite_id,- } = tokenValidationInfo || {}-- const loginRedirectLink = `/?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`-- const { mutate: joinOrganization } = useOrganizationJoinMutation({- onSuccess: () => {- setIsSubmitting(false)- router.push('/')- },- onError: (error) => {- toast.error(`Failed to join organization: ${error.message}`)- setIsSubmitting(false)- },- })-- const { mutate: declineOrganization } = useOrganizationJoinDeclineMutation({- onSuccess: () => {- setIsSubmitting(false)- router.push('/')- },- onError: (error) => {- toast.error(`Failed to decline invitation: ${error.message}`)- setIsSubmitting(false)- },- })-- useEffect(() => {- const fetchTokenInfo = async () => {- if (!slug) return console.error('Slug is required')- if (!token) return console.error('Token is required')-- try {- const response = await validateTokenInformation({ slug, token })- setTokenInfoLoaded(true)- setTokenValidationInfo(response)- } catch (error) {- setError(error)- setTokenInfoLoaded(true)- }- }-- if (!tokenInfoLoaded && token) {- fetchTokenInfo()- }-- /**- * if params are empty then redirect- * user to the homepage of app- */- // if (!slug && !token) router.push('/')- }, [token, router.asPath])-- async function handleJoinOrganization() {- if (!slug) return console.error('Slug is required')- if (!token) return console.error('Token is required')- setIsSubmitting(true)- joinOrganization({ slug, token })- }-- async function handleDeclineJoinOrganization() {- if (!slug) return console.error('Slug is required')- if (!invite_id) return console.error('Invite ID is required')- setIsSubmitting(true)- declineOrganization({ slug, invited_id: invite_id })- }-- const isError =- error ||- !!(tokenInfoLoaded && sso_mismatch) ||- !!(tokenInfoLoaded && token_does_not_exist) ||- (tokenInfoLoaded && !email_match) ||- (tokenInfoLoaded && expired_token)-- const ErrorMessage = () => {- const Container = ({ children }: { children: React.ReactNode }) => (- <div- className={[- 'flex flex-col items-center justify-center gap-3 text-sm',- isError ? 'text-foreground-light' : 'text-foreground',- ].join(' ')}- >- {children}- </div>- )-- const message = error ? (- <p>There was an error requesting details for this invitation. ({error.message})</p>- ) : sso_mismatch ? (- <>- <p>SSO providers do not match.</p>- <p className="text-foreground-lighter">- This invitation comes from a different identity provider than the one you are currently- logged in with. Please use the same SSO provider instead.- </p>- </>- ) : token_does_not_exist ? (- <>- <p>The invite token is invalid.</p>- <p className="text-foreground-lighter">- Try copying and pasting the link from the invite email, or ask the organization owner to- invite you again.- </p>- </>- ) : !email_match ? (- <>- <p>- Your email address {profile?.primary_email} does not match the email address this- invitation was sent to.- </p>- <p className="text-foreground-lighter">- To accept this invitation, you will need to{' '}- <a- className="cursor-pointer text-brand"- onClick={async () => {- await signOut()- router.reload()- }}- >- sign out- </a>{' '}- and then sign in or create a new account using the same email address used in the- invitation.- </p>- </>- ) : expired_token ? (- <>- <p>The invite token has expired.</p>- <p className="text-foreground-lighter">- Please request a new one from the organization owner.- </p>- </>- ) : (- ''- )-- return isError ? <Container>{message}</Container> : null- }-- const Content = () => (- <>- <div className="flex flex-col gap-2 px-6 py-8">- <>- <p className="text-sm text-foreground">You have been invited to join </p>- {organization_name ? (- <>- <p className="text-3xl text-foreground">- {name ? name : organization_name ? `${organization_name}` : 'an organization'}- </p>- {!token_does_not_exist && (- <p className="text-sm text-foreground-lighter">an organization on Supabase</p>- )}- </>- ) : (- <>- <p className="text-3xl text-foreground">{'an organization'}</p>- </>- )}- {slug && (- <p className="text-xs text-foreground-lighter">{`organization slug: ${slug}`}</p>- )}- </>- </div>-- <div- className={['border-t border-muted', isError ? 'bg-alternative' : 'bg-transparent'].join(- ' '- )}- >- <div className="flex flex-col gap-4 px-6 py-4 ">- {profile && !isError && (- <div className="flex flex-row items-center justify-center gap-3">- <Button onClick={handleDeclineJoinOrganization} htmlType="submit" type="default">- Decline- </Button>- <Button- onClick={handleJoinOrganization}- htmlType="submit"- loading={isSubmitting}- type="primary"- icon={<IconCheckSquare />}- >- Join organization- </Button>- </div>- )}-- {tokenInfoLoaded && <ErrorMessage />}-- {!profile && (- <div className="flex flex-col gap-3">- <p className="text-xs text-foreground-lighter">- You will need to sign in to accept this invitation- </p>- <div className="flex justify-center gap-3">- <Button asChild type="default">- <Link href={loginRedirectLink}>Sign in</Link>- </Button>- <Button asChild type="default">- <Link href={loginRedirectLink}>Create an account</Link>- </Button>- </div>- </div>- )}- </div>- </div>- </>- )-- return (- <div- className={[- 'flex h-full min-h-screen bg-studio',- 'w-full flex-col place-items-center',- 'items-center justify-center gap-8 px-5',- ].join(' ')}- >- <Link href="/projects" className="flex items-center justify-center gap-4">- <img- src={`${router.basePath}/img/supabase-logo.svg`}- alt="Supabase"- className="block h-[24px] cursor-pointer rounded"- />- </Link>- <div- className="- mx-auto overflow-hidden rounded-md border- border-muted bg-alternative text-center shadow- md:w-[400px]- "- >- <Loading active={!tokenInfoLoaded}>- <Content />- </Loading>- </div>- </div>- )-}--export default JoinOrganizationPagediff --git a/apps/studio/pages/project/[ref]/database/backups/pitr.tsx b/apps/studio/pages/project/[ref]/database/backups/pitr.tsxindex 8ca1607c74a..12846c00f0e 100644--- a/apps/studio/pages/project/[ref]/database/backups/pitr.tsx+++ b/apps/studio/pages/project/[ref]/database/backups/pitr.tsx@@ -58,8 +58,8 @@ const PITR = () => {const plan = subscription?.plan?.idconst isEnabled = backups?.pitr_enabled- const canReadPhysicalBackups = useCheckPermissions(PermissionAction.READ, 'physical_backups')const isPermissionsLoaded = usePermissionsLoaded()+ const canReadPhysicalBackups = useCheckPermissions(PermissionAction.READ, 'physical_backups')if (isPermissionsLoaded && !canReadPhysicalBackups) {return <NoPermission resourceText="view PITR backups" />diff --git a/apps/studio/pages/project/[ref]/database/backups/scheduled.tsx b/apps/studio/pages/project/[ref]/database/backups/scheduled.tsxindex ed71ee3b923..8f6db257057 100644--- a/apps/studio/pages/project/[ref]/database/backups/scheduled.tsx+++ b/apps/studio/pages/project/[ref]/database/backups/scheduled.tsx@@ -1,4 +1,5 @@import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Info } from 'lucide-react'import { BackupsList } from 'components/interfaces/Database'import DatabaseBackupsNav from 'components/interfaces/Database/Backups/DatabaseBackupsNav'@@ -13,7 +14,6 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useBackupsQuery } from 'data/database/backups-query'import { useCheckPermissions, usePermissionsLoaded } from 'hooks'import type { NextPageWithLayout } from 'types'-import { IconInfo } from 'ui'const DatabaseScheduledBackups: NextPageWithLayout = () => {const { project } = useProjectContext()@@ -28,9 +28,10 @@ const DatabaseScheduledBackups: NextPageWithLayout = () => {} = useBackupsQuery({ projectRef: ref })const isPitrEnabled = backups?.pitr_enabled- const canReadScheduledBackups = useCheckPermissions(PermissionAction.READ, 'back_ups')const isPermissionsLoaded = usePermissionsLoaded()+ const canReadScheduledBackups = useCheckPermissions(PermissionAction.READ, 'back_ups')+return (<ScaffoldContainer><ScaffoldSection>@@ -39,7 +40,7 @@ const DatabaseScheduledBackups: NextPageWithLayout = () => {<FormHeader className="!mb-0" title="Database Backups" /><DatabaseBackupsNav active="scheduled" projRef={ref} />- <div className="space-y-8">+ <div className="flex flex-col gap-y-4">{isLoading && <GenericSkeletonLoader />}{isError && (@@ -59,7 +60,7 @@ const DatabaseScheduledBackups: NextPageWithLayout = () => {<InformationBoxhideCollapsedefaultVisibility- icon={<IconInfo strokeWidth={2} />}+ icon={<Info strokeWidth={2} />}title="Point-In-Time-Recovery (PITR) enabled"description={<div>diff --git a/apps/studio/types/base.ts b/apps/studio/types/base.tsindex 118c9591ee1..f9ce8894442 100644--- a/apps/studio/types/base.ts+++ b/apps/studio/types/base.ts@@ -80,6 +80,8 @@ export interface Permission {condition: jsonLogic.RulesLogicorganization_id: numberresources: string[]+ restrictive?: boolean+ project_ids?: number[]}export interface ResponseFailure {diff --git a/package-lock.json b/package-lock.jsonindex 1c6730c6d9d..c151fa40fbf 100644--- a/package-lock.json+++ b/package-lock.json@@ -1238,7 +1238,7 @@"@supabase/auth-helpers-react": "^0.4.2","@supabase/pg-meta": "*","@supabase/realtime-js-next": "npm:@supabase/[email protected]",- "@supabase/shared-types": "0.1.65",+ "@supabase/shared-types": "0.1.70","@supabase/supabase-js": "^2.41.1","@tanstack/react-query": "4.35.7","@tanstack/react-query-devtools": "4.35.7",@@ -1272,7 +1272,6 @@"next-themes": "^0.3.0","openai": "^4.20.1","openapi-fetch": "^0.6.2",- "p-queue": "^6.6.2","papaparse": "^5.3.1","path-to-regexp": "^6.2.0","pg-minify": "^1.6.3",@@ -13689,9 +13688,9 @@}},"node_modules/@supabase/shared-types": {- "version": "0.1.65",- "resolved": "https://registry.npmjs.org/@supabase/shared-types/-/shared-types-0.1.65.tgz",- "integrity": "sha512-MPOaMkUlysDlP51e0h0PTIAXAPJwHvRb1szjxW2SRrCmH1dmKtg5PuwtR2sWAGRCajjutgx1ofPZuIYXj5mvzQ=="+ "version": "0.1.70",+ "resolved": "https://registry.npmjs.org/@supabase/shared-types/-/shared-types-0.1.70.tgz",+ "integrity": "sha512-Z/JBbISlxMcOjFcomZdB5AGKrQdTy/dy3HQ8EpHx3xKz1yktbUDrzVcEFUKidRPrQu1GAt9JSW6qBsBlXHcyLA=="},"node_modules/@supabase/sql-to-rest": {"version": "0.1.6",@@ -32397,13 +32396,6 @@"integrity": "sha512-Ou3dJ6bA/UJ5GVHxah4LnqDwZRwAmWxrG3wtrHrbGnP4RnLCtA64A4F+ae7Y8ww660JaddSoArUR5HjipWSHAQ==","dev": true},- "node_modules/p-finally": {- "version": "1.0.0",- "license": "MIT",- "engines": {- "node": ">=4"- }- },"node_modules/p-limit": {"version": "3.1.0","license": "MIT",@@ -32443,30 +32435,6 @@"url": "https://github.com/sponsors/sindresorhus"}},- "node_modules/p-queue": {- "version": "6.6.2",- "license": "MIT",- "dependencies": {- "eventemitter3": "^4.0.4",- "p-timeout": "^3.2.0"- },- "engines": {- "node": ">=8"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"- }- },- "node_modules/p-timeout": {- "version": "3.2.0",- "license": "MIT",- "dependencies": {- "p-finally": "^1.0.0"- },- "engines": {- "node": ">=8"- }- },"node_modules/p-try": {"version": "2.2.0","dev": true,diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.tsindex 29b53f47670..0c1d0585436 100644--- a/packages/api-types/types/api.d.ts+++ b/packages/api-types/types/api.d.ts@@ -365,6 +365,30 @@ export interface paths {/** Gets organization members who have reached their free project limit */get: operations['ReachedFreeProjectLimitController_getMembersWhoReachedFreeProjectLimit']}+ '/platform/organizations/{slug}/oauth/apps': {+ /** List published or authorized oauth apps */+ get: operations['OAuthAppsController_listOAuthApps']+ /** Create an oauth app */+ post: operations['OAuthAppsController_createOAuthApp']+ }+ '/platform/organizations/{slug}/oauth/apps/{id}': {+ /** Update an oauth app */+ put: operations['OAuthAppsController_updateOAuthApp']+ /** Remove a published oauth app */+ delete: operations['OAuthAppsController_removeOAuthApp']+ }+ '/platform/organizations/{slug}/oauth/apps/{id}/revoke': {+ /** Revoke an authorized oauth app */+ post: operations['OAuthAppsController_revokeAuthorizedOAuthApp']+ }+ '/platform/organizations/{slug}/oauth/authorizations/{id}': {+ /** [Beta] Get oauth app authorization request */+ get: operations['AuthorizationsController_getAuthorizationRequest']+ /** [Beta] Approve oauth app authorization request */+ post: operations['AuthorizationsController_approveAuthorizationRequest']+ /** [Beta] Decline oauth app authorization request */+ delete: operations['AuthorizationsController_declineAuthorizationRequest']+ }'/platform/organizations/{slug}/payments': {/** Gets Stripe payment methods for the given organization */get: operations['getPaymentMethodsV2']@@ -635,50 +659,6 @@ export interface paths {/** Gets project's usage api requests count */get: operations['UsageApiController_getApiRequestsCount']}- '/platform/projects/{ref}/analytics/warehouse/access-tokens': {- /** Lists project's warehouse access tokens from logflare */- get: operations['AccessTokenController_listAccessTokens']- /** Create a warehouse access token */- post: operations['AccessTokenController_createAccessToken']- }- '/platform/projects/{ref}/analytics/warehouse/access-tokens/{token}': {- /** Delete a warehouse access token */- delete: operations['AccessTokenController_deleteAccessToken']- }- '/platform/projects/{ref}/analytics/warehouse/collections': {- /** Lists project's warehouse collections from logflare */- get: operations['CollectionController_listCollections']- /** Create a warehouse collection */- post: operations['CollectionController_createCollection']- }- '/platform/projects/{ref}/analytics/warehouse/collections/{token}': {- /** Get a warehouse collection */- get: operations['CollectionController_getCollection']- /** Delete a warehouse collection */- delete: operations['CollectionController_deleteCollection']- /** Update a warehouse collection */- patch: operations['CollectionController_updateCollection']- }- '/platform/projects/{ref}/analytics/warehouse/endpoints': {- /** Lists project's warehouse endpoints from logflare */- get: operations['EndpointController_listEndpoints']- /** Create a warehouse endpoint */- post: operations['EndpointController_createEndpoint']- }- '/platform/projects/{ref}/analytics/warehouse/endpoints/{token}': {- /** Update a warehouse endpoint */- put: operations['EndpointController_updateEndpoint']- /** Delete a warehouse endpoint */- delete: operations['EndpointController_deleteEndpoint']- }- '/platform/projects/{ref}/analytics/warehouse/query': {- /** Lists project's warehouse queries from logflare */- get: operations['WarehouseQueryController_runQuery']- }- '/platform/projects/{ref}/analytics/warehouse/tenant': {- /** Gets project's warehouse tenant from logflare */- get: operations['TenantController_getTenant']- }'/platform/projects/{ref}/api/graphql': {/** Queries project Graphql */post: operations['ProjectsApiController_projectGraphql']@@ -820,8 +800,8 @@ export interface paths {post: operations['RestartServicesController_restartServices']}'/platform/projects/{ref}/restore': {- /** Restores project */- post: operations['RestoreController_restoreProject']+ /** Cancels a failed restoration */+ post: operations['RestoreController_cancelProjectRestoration']}'/platform/projects/{ref}/run-lints': {/** Run project lints */@@ -1458,50 +1438,6 @@ export interface paths {/** Gets project's usage api requests count */get: operations['UsageApiController_getApiRequestsCount']}- '/v0/projects/{ref}/analytics/warehouse/access-tokens': {- /** Lists project's warehouse access tokens from logflare */- get: operations['AccessTokenController_listAccessTokens']- /** Create a warehouse access token */- post: operations['AccessTokenController_createAccessToken']- }- '/v0/projects/{ref}/analytics/warehouse/access-tokens/{token}': {- /** Delete a warehouse access token */- delete: operations['AccessTokenController_deleteAccessToken']- }- '/v0/projects/{ref}/analytics/warehouse/collections': {- /** Lists project's warehouse collections from logflare */- get: operations['CollectionController_listCollections']- /** Create a warehouse collection */- post: operations['CollectionController_createCollection']- }- '/v0/projects/{ref}/analytics/warehouse/collections/{token}': {- /** Get a warehouse collection */- get: operations['CollectionController_getCollection']- /** Delete a warehouse collection */- delete: operations['CollectionController_deleteCollection']- /** Update a warehouse collection */- patch: operations['CollectionController_updateCollection']- }- '/v0/projects/{ref}/analytics/warehouse/endpoints': {- /** Lists project's warehouse endpoints from logflare */- get: operations['EndpointController_listEndpoints']- /** Create a warehouse endpoint */- post: operations['EndpointController_createEndpoint']- }- '/v0/projects/{ref}/analytics/warehouse/endpoints/{token}': {- /** Update a warehouse endpoint */- put: operations['EndpointController_updateEndpoint']- /** Delete a warehouse endpoint */- delete: operations['EndpointController_deleteEndpoint']- }- '/v0/projects/{ref}/analytics/warehouse/query': {- /** Lists project's warehouse queries from logflare */- get: operations['WarehouseQueryController_runQuery']- }- '/v0/projects/{ref}/analytics/warehouse/tenant': {- /** Gets project's warehouse tenant from logflare */- get: operations['TenantController_getTenant']- }'/v0/projects/{ref}/api/graphql': {/** Queries project Graphql */post: operations['ProjectsApiController_projectGraphql']@@ -1625,8 +1561,8 @@ export interface paths {post: operations['RestartServicesController_restartServices']}'/v0/projects/{ref}/restore': {- /** Restores project */- post: operations['RestoreController_restoreProject']+ /** Cancels a failed restoration */+ post: operations['RestoreController_cancelProjectRestoration']}'/v0/projects/{ref}/settings': {/** Gets project's settings */@@ -1772,7 +1708,51 @@ export interface paths {}'/v1/projects/{ref}': {/** Deletes the given project */- delete: operations['v1-Delete a project']+ delete: operations['v1-delete-a-project']+ }+ '/v1/projects/{ref}/analytics/warehouse/access-tokens': {+ /** Lists project's warehouse access tokens from logflare */+ get: operations['v1-list-all-warehouse-tokens']+ /** Create a warehouse access token */+ post: operations['v1-create-a-warehouse-token']+ }+ '/v1/projects/{ref}/analytics/warehouse/access-tokens/{token}': {+ /** Delete a warehouse access token */+ delete: operations['v1-delete-a-warehouse-token']+ }+ '/v1/projects/{ref}/analytics/warehouse/collections': {+ /** Lists project's warehouse collections from logflare */+ get: operations['v1-list-all-warehouse-collections']+ /** Create a warehouse collection */+ post: operations['v1-create-a-warehouse-collection']+ }+ '/v1/projects/{ref}/analytics/warehouse/collections/{token}': {+ /** Get a warehouse collection */+ get: operations['v1-get-a-warehouse-collection']+ /** Delete a warehouse collection */+ delete: operations['v1-delete-a-warehouse-collection']+ /** Update a warehouse collection */+ patch: operations['v1-update-a-warehouse-collection']+ }+ '/v1/projects/{ref}/analytics/warehouse/endpoints': {+ /** Lists project's warehouse endpoints from logflare */+ get: operations['v1-list-all-warehouse-endpoints']+ /** Create a warehouse endpoint */+ post: operations['v1-create-a-warehouse-endpoint']+ }+ '/v1/projects/{ref}/analytics/warehouse/endpoints/{token}': {+ /** Update a warehouse endpoint */+ put: operations['v1-update-a-warehouse-endpoint']+ /** Delete a warehouse endpoint */+ delete: operations['v1-delete-a-warehouse-endpoint']+ }+ '/v1/projects/{ref}/analytics/warehouse/query': {+ /** Lists project's warehouse queries from logflare */+ get: operations['v1-list-all-warehouse-queries']+ }+ '/v1/projects/{ref}/analytics/warehouse/tenant': {+ /** Gets project's warehouse tenant from logflare */+ get: operations['v1-provision-a-warehouse-tenant']}'/v1/projects/{ref}/api-keys': {/** Get project api keys */@@ -2081,6 +2061,9 @@ export interface components {ApiResponse: {autoApiService: components['schemas']['AutoApiService']}+ ApproveAuthorizationResponse: {+ url: string+ }AssignMemberRoleBodyV2: {role_id: numberrole_scoped_projects?: string[]@@ -2266,6 +2249,9 @@ export interface components {name: stringversion: string}+ AuthorizationsApproveBody: {+ organization_id: string+ }AutoApiService: {app: {id?: number@@ -2527,6 +2513,41 @@ export interface components {role_id: numberrole_scoped_projects?: string[]}+ CreateOAuthAppBody: {+ icon?: string+ name: string+ redirect_uris: string[]+ scopes?: (+ | 'analytics:read'+ | 'analytics:write'+ | 'auth:read'+ | 'auth:write'+ | 'database:read'+ | 'database:write'+ | 'domains:read'+ | 'domains:write'+ | 'edge_functions:read'+ | 'edge_functions:write'+ | 'environment:read'+ | 'environment:write'+ | 'organizations:read'+ | 'organizations:write'+ | 'projects:read'+ | 'projects:write'+ | 'rest:read'+ | 'rest:write'+ | 'secrets:read'+ | 'secrets:write'+ | 'storage:read'+ | 'storage:write'+ )[]+ website: string+ }+ CreateOAuthAppResponse: {+ client_id: string+ client_secret: string+ id: string+ }CreateOrganizationBody: {kind?: stringname: string@@ -2798,6 +2819,7 @@ export interface components {| '6_volume_detachchment_from_original_instance_failed'| '7_volume_attachment_to_upgraded_instance_failed'| '8_upgrade_completion_failed'+ | '9_post_physical_backup_failed'initiated_at: string/** @enum {string} */progress?:@@ -2811,6 +2833,7 @@ export interface components {| '7_detached_volume_from_original_instance'| '8_attached_volume_to_upgraded_instance'| '9_completed_upgrade'+ | '10_completed_post_physical_backup'/** @enum {number} */status: 0 | 1 | 2target_version: number@@ -2831,6 +2854,19 @@ export interface components {| '8xlarge'| '12xlarge'| '16xlarge'+ DeclineAuthorizationResponse: {+ id: string+ }+ DeleteOAuthAppResponse: {+ client_id: string+ client_secret_alias: string+ created_at: string+ icon?: string+ id: string+ name: string+ redirect_uris: string[]+ website: string+ }DeleteObjectsBody: {paths: string[]}@@ -2981,6 +3017,39 @@ export interface components {verify_jwt?: booleanversion: number}+ GetAuthorizationResponse: {+ approved_at?: string+ approved_organization_slug?: string+ domain: string+ expires_at: string+ icon?: string+ name: string+ scopes?: (+ | 'analytics:read'+ | 'analytics:write'+ | 'auth:read'+ | 'auth:write'+ | 'database:read'+ | 'database:write'+ | 'domains:read'+ | 'domains:write'+ | 'edge_functions:read'+ | 'edge_functions:write'+ | 'environment:read'+ | 'environment:write'+ | 'organizations:read'+ | 'organizations:write'+ | 'projects:read'+ | 'projects:write'+ | 'rest:read'+ | 'rest:write'+ | 'secrets:read'+ | 'secrets:write'+ | 'storage:read'+ | 'storage:write'+ )[]+ website: string+ }GetMetricsBody: {/** @enum {string} */interval: '1d' | '3d' | '7d'@@ -3381,6 +3450,7 @@ export interface components {expired_token: booleaninvite_id?: numberorganization_name: string+ sso_mismatch: booleantoken_does_not_exist: boolean}InvitationResponse: {@@ -3594,6 +3664,41 @@ export interface components {has_warning: booleanunread_count: number}+ OAuthAppResponse: {+ authorized_at?: string+ client_id?: string+ client_secret_alias?: string+ created_at?: string+ icon?: string+ id: string+ name: string+ redirect_uris?: string[]+ scopes?: (+ | 'analytics:read'+ | 'analytics:write'+ | 'auth:read'+ | 'auth:write'+ | 'database:read'+ | 'database:write'+ | 'domains:read'+ | 'domains:write'+ | 'edge_functions:read'+ | 'edge_functions:write'+ | 'environment:read'+ | 'environment:write'+ | 'organizations:read'+ | 'organizations:write'+ | 'projects:read'+ | 'projects:write'+ | 'rest:read'+ | 'rest:write'+ | 'secrets:read'+ | 'secrets:write'+ | 'storage:read'+ | 'storage:write'+ )[]+ website: string+ }OAuthTokenBody: {client_id: stringclient_secret: string@@ -3660,7 +3765,7 @@ export interface components {name: string}OrganizationRole: {- description: string+ description: string | nullid: numbername: string}@@ -3670,10 +3775,10 @@ export interface components {}OrganizationRoleV2: {base_role_id: number- description: string+ description: string | nullid: numbername: string- project_ids: number[]+ project_ids: number[] | null}OrganizationSlugResponse: {billing_email?: string@@ -3783,6 +3888,7 @@ export interface components {Permission: {actions: (| 'analytics:Read'+ | 'analytics:Write'| 'auth:Execute'| 'billing:Read'| 'billing:Write'@@ -4348,6 +4454,16 @@ export interface components {PublicUrlResponse: {publicUrl: string}+ PutOAuthAppResponse: {+ client_id: string+ client_secret_alias: string+ created_at: string+ icon?: string+ id: string+ name: string+ redirect_uris: string[]+ website: string+ }ReadOnlyStatusResponse: {enabled: booleanoverride_active_until: string@@ -4532,6 +4648,7 @@ export interface components {RestartServicesBody: {restartRequest: components['schemas']['RestartServiceRequest']}+ RestoreCancellation: Record<string, never>RestoreLogicalBackupBody: {id: number}@@ -4564,6 +4681,13 @@ export interface components {| 'overdue_payment')[]}+ RevokeAuthorizedOAuthAppResponse: {+ authorized_at?: string+ icon?: string+ id: string+ name: string+ website: string+ }RevokeColumnPrivilegesBody: {column_id: stringgrantee: string@@ -6883,6 +7007,9 @@ export interface operations {204: {content: never}+ 403: {+ content: never+ }/** @description Failed to update GitHub connection */500: {content: never@@ -7241,6 +7368,9 @@ export interface operations {'application/json': components['schemas']['AuditLogsResponse']}}+ 403: {+ content: never+ }/** @description Failed to get an organization's audit logs */500: {content: never@@ -7459,7 +7589,7 @@ export interface operations {403: {content: never}- /** @description Failed to update subscription change */+ /** @description Failed to delete upcoming subscription schedule */500: {content: never}@@ -7976,6 +8106,164 @@ export interface operations {}}}+ /** List published or authorized oauth apps */+ OAuthAppsController_listOAuthApps: {+ parameters: {+ query: {+ type: 'published' | 'authorized'+ }+ path: {+ /** @description Organization slug */+ slug: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['OAuthAppResponse'][]+ }+ }+ 403: {+ content: never+ }+ }+ }+ /** Create an oauth app */+ OAuthAppsController_createOAuthApp: {+ parameters: {+ path: {+ /** @description Organization slug */+ slug: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['CreateOAuthAppBody']+ }+ }+ responses: {+ 201: {+ content: {+ 'application/json': components['schemas']['CreateOAuthAppResponse']+ }+ }+ 403: {+ content: never+ }+ }+ }+ /** Update an oauth app */+ OAuthAppsController_updateOAuthApp: {+ parameters: {+ path: {+ slug: string+ id: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['CreateOAuthAppBody']+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['PutOAuthAppResponse']+ }+ }+ 403: {+ content: never+ }+ }+ }+ /** Remove a published oauth app */+ OAuthAppsController_removeOAuthApp: {+ parameters: {+ path: {+ slug: string+ id: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['DeleteOAuthAppResponse']+ }+ }+ 403: {+ content: never+ }+ }+ }+ /** Revoke an authorized oauth app */+ OAuthAppsController_revokeAuthorizedOAuthApp: {+ parameters: {+ path: {+ slug: string+ id: string+ }+ }+ responses: {+ 201: {+ content: {+ 'application/json': components['schemas']['RevokeAuthorizedOAuthAppResponse']+ }+ }+ 403: {+ content: never+ }+ }+ }+ /** [Beta] Get oauth app authorization request */+ AuthorizationsController_getAuthorizationRequest: {+ parameters: {+ path: {+ id: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['GetAuthorizationResponse']+ }+ }+ }+ }+ /** [Beta] Approve oauth app authorization request */+ AuthorizationsController_approveAuthorizationRequest: {+ parameters: {+ path: {+ id: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['AuthorizationsApproveBody']+ }+ }+ responses: {+ 201: {+ content: {+ 'application/json': components['schemas']['ApproveAuthorizationResponse']+ }+ }+ }+ }+ /** [Beta] Decline oauth app authorization request */+ AuthorizationsController_declineAuthorizationRequest: {+ parameters: {+ path: {+ id: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['DeclineAuthorizationResponse']+ }+ }+ }+ }/** Gets Stripe payment methods for the given organization */getPaymentMethodsV2: {parameters: {@@ -10297,286 +10585,24 @@ export interface operations {}}}- /** Lists project's warehouse access tokens from logflare */- AccessTokenController_listAccessTokens: {+ /** Queries project Graphql */+ ProjectsApiController_projectGraphql: {parameters: {+ header: {+ 'x-graphql-authorization': string+ }path: {/** @description Project ref */ref: string}}+ requestBody: {+ content: {+ 'application/json': components['schemas']['Buffer']+ }+ }responses: {- 200: {- content: {- 'application/json': components['schemas']['LFAccessToken'][]- }- }- 403: {- content: never- }- /** @description Failed to fetch warehouse access tokens */- 500: {- content: never- }- }- }- /** Create a warehouse access token */- AccessTokenController_createAccessToken: {- responses: {- 201: {- content: {- 'application/json': components['schemas']['LFAccessToken']- }- }- 403: {- content: never- }- /** @description Failed to create warehouse access token */- 500: {- content: never- }- }- }- /** Delete a warehouse access token */- AccessTokenController_deleteAccessToken: {- responses: {- 200: {- content: never- }- 403: {- content: never- }- /** @description Failed to delete warehouse access token */- 500: {- content: never- }- }- }- /** Lists project's warehouse collections from logflare */- CollectionController_listCollections: {- parameters: {- path: {- /** @description Project ref */- ref: string- }- }- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFSource'][]- }- }- 403: {- content: never- }- /** @description Failed to fetch warehouse collections */- 500: {- content: never- }- }- }- /** Create a warehouse collection */- CollectionController_createCollection: {- responses: {- 201: {- content: {- 'application/json': components['schemas']['LFSource']- }- }- 403: {- content: never- }- /** @description Failed to create warehouse collection */- 500: {- content: never- }- }- }- /** Get a warehouse collection */- CollectionController_getCollection: {- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFSource']- }- }- 403: {- content: never- }- /** @description Failed to fetch warehouse collection */- 500: {- content: never- }- }- }- /** Delete a warehouse collection */- CollectionController_deleteCollection: {- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFSource']- }- }- 403: {- content: never- }- /** @description Failed to delete warehouse collection */- 500: {- content: never- }- }- }- /** Update a warehouse collection */- CollectionController_updateCollection: {- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFSource']- }- }- 403: {- content: never- }- /** @description Failed to update warehouse collection */- 500: {- content: never- }- }- }- /** Lists project's warehouse endpoints from logflare */- EndpointController_listEndpoints: {- parameters: {- path: {- /** @description Project ref */- ref: string- }- }- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFEndpoint'][]- }- }- 403: {- content: never- }- /** @description Failed to fetch warehouse endpoints */- 500: {- content: never- }- }- }- /** Create a warehouse endpoint */- EndpointController_createEndpoint: {- responses: {- 201: {- content: {- 'application/json': components['schemas']['LFEndpoint']- }- }- 403: {- content: never- }- /** @description Failed to create warehouse endpoint */- 500: {- content: never- }- }- }- /** Update a warehouse endpoint */- EndpointController_updateEndpoint: {- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFEndpoint']- }- }- 403: {- content: never- }- /** @description Failed to update warehouse endpoint */- 500: {- content: never- }- }- }- /** Delete a warehouse endpoint */- EndpointController_deleteEndpoint: {- responses: {- 200: {- content: never- }- 403: {- content: never- }- /** @description Failed to delete warehouse endpoint */- 500: {- content: never- }- }- }- /** Lists project's warehouse queries from logflare */- WarehouseQueryController_runQuery: {- parameters: {- path: {- /** @description Project ref */- ref: string- }- }- responses: {- 200: {- content: never- }- 403: {- content: never- }- /** @description Failed to fetch warehouse endpoints */- 500: {- content: never- }- }- }- /** Gets project's warehouse tenant from logflare */- TenantController_getTenant: {- parameters: {- path: {- /** @description Project ref */- ref: string- }- }- responses: {- 200: {- content: {- 'application/json': components['schemas']['LFUser']- }- }- 403: {- content: never- }- /** @description Failed to fetch or provision warehouse tenant */- 500: {- content: never- }- }- }- /** Queries project Graphql */- ProjectsApiController_projectGraphql: {- parameters: {- header: {- 'x-graphql-authorization': string- }- path: {- /** @description Project ref */- ref: string- }- }- requestBody: {- content: {- 'application/json': components['schemas']['Buffer']- }- }- responses: {- 201: {+ 201: {content: {'application/json': Record<string, never>}@@ -11487,8 +11513,8 @@ export interface operations {}}}- /** Restores project */- RestoreController_restoreProject: {+ /** Cancels a failed restoration */+ RestoreController_cancelProjectRestoration: {parameters: {path: {/** @description Project ref */@@ -11498,10 +11524,10 @@ export interface operations {responses: {201: {content: {- 'application/json': components['schemas']['RestoreProjectInfo']+ 'application/json': components['schemas']['RestoreCancellation']}}- /** @description Failed to restore project */+ /** @description Failed to cancel project restoration */500: {content: never}@@ -13397,7 +13423,7 @@ export interface operations {}}/** Deletes the given project */- 'v1-Delete a project': {+ 'v1-delete-a-project': {parameters: {path: {/** @description Project ref */@@ -13415,6 +13441,268 @@ export interface operations {}}}+ /** Lists project's warehouse access tokens from logflare */+ 'v1-list-all-warehouse-tokens': {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFAccessToken'][]+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to fetch warehouse access tokens */+ 500: {+ content: never+ }+ }+ }+ /** Create a warehouse access token */+ 'v1-create-a-warehouse-token': {+ responses: {+ 201: {+ content: {+ 'application/json': components['schemas']['LFAccessToken']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to create warehouse access token */+ 500: {+ content: never+ }+ }+ }+ /** Delete a warehouse access token */+ 'v1-delete-a-warehouse-token': {+ responses: {+ 200: {+ content: never+ }+ 403: {+ content: never+ }+ /** @description Failed to delete warehouse access token */+ 500: {+ content: never+ }+ }+ }+ /** Lists project's warehouse collections from logflare */+ 'v1-list-all-warehouse-collections': {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFSource'][]+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to fetch warehouse collections */+ 500: {+ content: never+ }+ }+ }+ /** Create a warehouse collection */+ 'v1-create-a-warehouse-collection': {+ responses: {+ 201: {+ content: {+ 'application/json': components['schemas']['LFSource']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to create warehouse collection */+ 500: {+ content: never+ }+ }+ }+ /** Get a warehouse collection */+ 'v1-get-a-warehouse-collection': {+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFSource']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to fetch warehouse collection */+ 500: {+ content: never+ }+ }+ }+ /** Delete a warehouse collection */+ 'v1-delete-a-warehouse-collection': {+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFSource']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to delete warehouse collection */+ 500: {+ content: never+ }+ }+ }+ /** Update a warehouse collection */+ 'v1-update-a-warehouse-collection': {+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFSource']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to update warehouse collection */+ 500: {+ content: never+ }+ }+ }+ /** Lists project's warehouse endpoints from logflare */+ 'v1-list-all-warehouse-endpoints': {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFEndpoint'][]+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to fetch warehouse endpoints */+ 500: {+ content: never+ }+ }+ }+ /** Create a warehouse endpoint */+ 'v1-create-a-warehouse-endpoint': {+ responses: {+ 201: {+ content: {+ 'application/json': components['schemas']['LFEndpoint']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to create warehouse endpoint */+ 500: {+ content: never+ }+ }+ }+ /** Update a warehouse endpoint */+ 'v1-update-a-warehouse-endpoint': {+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFEndpoint']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to update warehouse endpoint */+ 500: {+ content: never+ }+ }+ }+ /** Delete a warehouse endpoint */+ 'v1-delete-a-warehouse-endpoint': {+ responses: {+ 200: {+ content: never+ }+ 403: {+ content: never+ }+ /** @description Failed to delete warehouse endpoint */+ 500: {+ content: never+ }+ }+ }+ /** Lists project's warehouse queries from logflare */+ 'v1-list-all-warehouse-queries': {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: never+ }+ 403: {+ content: never+ }+ /** @description Failed to fetch warehouse queries */+ 500: {+ content: never+ }+ }+ }+ /** Gets project's warehouse tenant from logflare */+ 'v1-provision-a-warehouse-tenant': {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['LFUser']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to fetch or provision warehouse tenant */+ 500: {+ content: never+ }+ }+ }/** Get project api keys */'v1-get-project-api-keys': {parameters: {@@ -14208,6 +14496,9 @@ export interface operations {201: {content: never}+ 403: {+ content: never+ }/** @description Failed to remove read replica */500: {content: never@@ -14231,6 +14522,9 @@ export interface operations {201: {content: never}+ 403: {+ content: never+ }/** @description Failed to set up read replica */500: {content: neverdiff --git a/packages/ui-patterns/Dialogs/TextConfirmModal.tsx b/packages/ui-patterns/Dialogs/TextConfirmModal.tsxindex bfbb61eeda0..19b0cfee4f1 100644--- a/packages/ui-patterns/Dialogs/TextConfirmModal.tsx+++ b/packages/ui-patterns/Dialogs/TextConfirmModal.tsx@@ -148,7 +148,7 @@ const TextConfirmModal = forwardRef<control={form.control}name="confirmValue"render={({ field }) => (- <FormItem_Shadcn_>+ <FormItem_Shadcn_ className="flex flex-col gap-y-1"><FormLabel_Shadcn_ {...label}>Type <span className="text-foreground break-all">{confirmString}</span> toconfirm.diff --git a/packages/ui-patterns/MultiSelectDeprecated/MultiSelectV2.tsx b/packages/ui-patterns/MultiSelectDeprecated/MultiSelectV2.tsxindex c9c55493307..adf8dd6361d 100644--- a/packages/ui-patterns/MultiSelectDeprecated/MultiSelectV2.tsx+++ b/packages/ui-patterns/MultiSelectDeprecated/MultiSelectV2.tsx@@ -101,10 +101,14 @@ export const MultiSelectV2 = ({if (!option) {return <></>} else if (isDisabled) {- return <BadgeDisabled key={id} name={value} />+ return <BadgeDisabled key={id} name={option.name} />} else {return (- <BadgeSelected key={id} name={value} handleRemove={() => handleChange(option)} />+ <BadgeSelected+ key={id}+ name={option.name}+ handleRemove={() => handleChange(option)}+ />)}})}diff --git a/packages/ui/src/components/SidePanel/SidePanel.tsx b/packages/ui/src/components/SidePanel/SidePanel.tsxindex d021a38962e..f2af725afcc 100644--- a/packages/ui/src/components/SidePanel/SidePanel.tsx+++ b/packages/ui/src/components/SidePanel/SidePanel.tsx@@ -1,9 +1,13 @@'use client'import * as Dialog from '@radix-ui/react-dialog'-import * as Tooltip from '@radix-ui/react-tooltip'import React from 'react'-import { Button } from '../../../index'+import {+ Button,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+} from '../../../index'import styleHandler from '../../lib/theme/styleHandler'export type SidePanelProps = RadixProps & CustomProps@@ -73,35 +77,21 @@ const SidePanel = ({</Button></div>{onConfirm !== undefined && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>- <div>- <Button- htmlType="submit"- disabled={disabled || loading}- loading={loading}- onClick={() => (onConfirm ? onConfirm() : null)}- >- {confirmText}- </Button>- </div>- </Tooltip.Trigger>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <Button+ htmlType="submit"+ disabled={disabled || loading}+ loading={loading}+ onClick={() => (onConfirm ? onConfirm() : null)}+ >+ {confirmText}+ </Button>+ </TooltipTrigger_Shadcn_>{tooltip !== undefined && (- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">{tooltip}</span>- </div>- </Tooltip.Content>- </Tooltip.Portal>+ <TooltipContent_Shadcn_ side="bottom">{tooltip}</TooltipContent_Shadcn_>)}- </Tooltip.Root>+ </Tooltip_Shadcn_>)}</div>)