The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: Update styling and more descriptive information for roles when inviting members (#46515)
Ali Waseem3e7d8d0f6892
diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsxindex 884a9c65035..ee9b857f01f 100644--- a/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx+++ b/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx@@ -7,24 +7,27 @@ import { useForm } from 'react-hook-form'import { toast } from 'sonner'import {Button,- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogSection,- DialogSectionSeparator,- DialogTitle,- DialogTrigger,ExpandingTextArea,Form,FormControl,FormField,+ FormItem,+ RadioGroupStacked,+ RadioGroupStackedItem,Select,SelectContent,SelectGroup,SelectItem,SelectTrigger,SelectValue,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetSection,+ SheetTitle,+ SheetTrigger,Switch,} from 'ui'import { Admonition } from 'ui-patterns/admonition'@@ -39,10 +42,12 @@ import {emailSchema,parseEmails,} from './InviteMemberButton.utils'+import { ROLE_DESCRIPTIONS } from './Roles.constants'import { useGetRolesManagementPermissions } from './TeamSettings.utils'import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { DocsButton } from '@/components/ui/DocsButton'+import { InlineLink } from '@/components/ui/InlineLink'import { OrganizationProjectSelector } from '@/components/ui/OrganizationProjectSelector'import { Shortcut } from '@/components/ui/Shortcut'import { UpgradePlanButton } from '@/components/ui/UpgradePlanButton'@@ -209,7 +214,7 @@ export const InviteMemberButton = () => {}if (succeeded.length > 0) {- closeInviteDialog()+ closeInviteSheet()}}@@ -228,7 +233,7 @@ export const InviteMemberButton = () => {const hasUnsavedChanges = form.formState.isDirty- const closeInviteDialog = () => {+ const closeInviteSheet = () => {setProjectDropdownOpen(false)setIsOpen(false)form.reset(defaultValues)@@ -240,12 +245,12 @@ export const InviteMemberButton = () => {modalProps: discardChangesModalProps,} = useConfirmOnClose({checkIsDirty: () => hasUnsavedChanges,- onClose: closeInviteDialog,+ onClose: closeInviteSheet,})return (- <Dialog open={isOpen} onOpenChange={handleOpenChange}>- <DialogTrigger asChild>+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>+ <SheetTrigger asChild><Shortcutid={SHORTCUT_IDS.ORG_TEAM_INVITE}onTrigger={() => {@@ -274,12 +279,14 @@ export const InviteMemberButton = () => {Invite members</ButtonTooltip></Shortcut>- </DialogTrigger>- <DialogContent size="medium">- <DialogHeader>- <DialogTitle>Invite team members</DialogTitle>- </DialogHeader>- <DialogSectionSeparator />+ </SheetTrigger>+ <SheetContent className="flex flex-col gap-0">+ <SheetHeader>+ <SheetTitle>Invite team members</SheetTitle>+ <SheetDescription>+ Send invitations and choose the access each new team member receives.+ </SheetDescription>+ </SheetHeader><Admonitiontype="note"showIcon={false}@@ -300,58 +307,62 @@ export const InviteMemberButton = () => {</>}/>- <Form {...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">+ <SheetSection className="grow overflow-auto">+ <Form {...form}>+ <form+ id="organization-invitation"+ className="flex flex-col gap-y-4"+ onSubmit={form.handleSubmit(onInviteMember)}+ ><FormFieldname="role"control={form.control}render={({ field }) => (- <FormItemLayout label="Role">- <FormControl>- <Select value={field.value} onValueChange={field.onChange}>- <SelectTrigger className="text-sm capitalize">- {orgScopedRoles.find((role) => role.id === Number(field.value))?.name ??- 'Unknown'}- </SelectTrigger>- <SelectContent>- <SelectGroup>- {orgScopedRoles.map((role) => {- const canAssignRole = rolesAddable.includes(role.id)- const isOwnerRole = role.name === 'Owner'- const disabledForStripe = isStripeProjectsOrg && isOwnerRole- const disabled = !canAssignRole || disabledForStripe- const disabledReason = disabledForStripe- ? 'Cannot be assigned in Stripe Projects organizations'- : !canAssignRole- ? 'Additional permissions required to assign role'- : undefined-- return (- <SelectItem- key={role.id}+ <FormItemLayout+ layout="horizontal"+ label="Role"+ description={+ <>+ Learn more about{' '}+ <InlineLink href={`${DOCS_URL}/guides/platform/access-control`}>+ roles and permissions+ </InlineLink>+ </>+ }+ >+ <FormControl className="col-span-6">+ <RadioGroupStacked value={field.value} onValueChange={field.onChange}>+ {orgScopedRoles.map((role) => {+ const canAssignRole = rolesAddable.includes(role.id)+ const isOwnerRole = role.name === 'Owner'+ const disabledForStripe = isStripeProjectsOrg && isOwnerRole+ const disabled = !canAssignRole || disabledForStripe+ const disabledReason = disabledForStripe+ ? 'Cannot be assigned in Stripe Projects organizations'+ : !canAssignRole+ ? 'Additional permissions required to assign role'+ : undefined++ return (+ <FormItem asChild key={role.id}>+ <FormControl>+ <RadioGroupStackedItemvalue={role.id.toString()}- className="text-sm"disabled={disabled}- >- <div className="flex flex-col gap-0.5">- <span>{role.name}</span>- {disabledReason && (- <span className="text-xs text-foreground-lighter">- {disabledReason}- </span>- )}- </div>- </SelectItem>- )- })}- </SelectGroup>- </SelectContent>- </Select>+ label={role.name}+ description={[+ ROLE_DESCRIPTIONS[role.name] ??+ 'Permissions are based on the configured organization role.',+ disabledReason,+ ]+ .filter(Boolean)+ .join(' ')}+ />+ </FormControl>+ </FormItem>+ )+ })}+ </RadioGroupStacked></FormControl></FormItemLayout>)}@@ -362,10 +373,11 @@ export const InviteMemberButton = () => {control={form.control}render={({ field }) => (<FormItemLayout+ layout="horizontal"label="Invitation type"description="Choose how the invitee should authenticate">- <FormControl>+ <FormControl className="col-span-6"><Select value={field.value} onValueChange={field.onChange}><SelectTrigger><SelectValue placeholder="Automatic (based on your account)" />@@ -390,8 +402,12 @@ export const InviteMemberButton = () => {name="applyToOrg"control={form.control}render={({ field }) => (- <FormItemLayout layout="flex" label="Grant this role on all projects">- <FormControl>+ <FormItemLayout+ layout="horizontal"+ label="Grant this role on all projects"+ description="Apply this role to all current and future projects in the organization"+ >+ <FormControl className="col-span-6"><Switch checked={field.value} onCheckedChange={field.onChange} /></FormControl></FormItemLayout>@@ -404,10 +420,11 @@ export const InviteMemberButton = () => {control={form.control}render={({ field }) => (<FormItemLayout+ layout="horizontal"label="Select a project"description="Project access can be adjusted after the user joins">- <FormControl>+ <FormControl className="col-span-6"><OrganizationProjectSelectorfetchOnMountsameWidthAsTrigger@@ -428,8 +445,8 @@ export const InviteMemberButton = () => {name="email"control={form.control}render={({ field }) => (- <FormItemLayout label="Email addresses">- <FormControl>+ <FormItemLayout layout="horizontal" label="Email addresses">+ <FormControl className="col-span-6"><ExpandingTextAreaautoFocus{...field}@@ -446,29 +463,34 @@ export const InviteMemberButton = () => {</FormItemLayout>)}/>- </DialogSection>- <DialogFooter className="justify-between!">- <Button type="default" onClick={confirmOnClose}>- Cancel- </Button>- <Shortcut- id={SHORTCUT_IDS.ORG_TEAM_INVITE_SUBMIT}- onTrigger={() => form.handleSubmit(onInviteMember)()}- options={{ enabled: isOpen && !isInviting }}- side="top"- >- <Button type="primary" htmlType="submit" loading={isInviting}>- {emailCount >= 2 ? 'Send invitations' : 'Send invitation'}- </Button>- </Shortcut>- </DialogFooter>- </form>- </Form>- </DialogContent>+ </form>+ </Form>+ </SheetSection>+ <SheetFooter>+ <Button type="default" onClick={confirmOnClose}>+ Cancel+ </Button>+ <Shortcut+ id={SHORTCUT_IDS.ORG_TEAM_INVITE_SUBMIT}+ onTrigger={() => form.handleSubmit(onInviteMember)()}+ options={{ enabled: isOpen && !isInviting }}+ side="top"+ >+ <Button+ type="primary"+ form="organization-invitation"+ htmlType="submit"+ loading={isInviting}+ >+ {emailCount >= 2 ? 'Send invitations' : 'Send invitation'}+ </Button>+ </Shortcut>+ </SheetFooter>+ </SheetContent><DiscardChangesConfirmationDialog{...discardChangesModalProps}description="Are you sure you want to discard your changes? Your invitation will not be sent."/>- </Dialog>+ </Sheet>)}diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/Roles.constants.ts b/apps/studio/components/interfaces/Organization/TeamSettings/Roles.constants.tsnew file mode 100644index 00000000000..56d9cef555c--- /dev/null+++ b/apps/studio/components/interfaces/Organization/TeamSettings/Roles.constants.ts@@ -0,0 +1,9 @@+export const ROLE_DESCRIPTIONS: Record<string, string> = {+ Owner: 'Full access, including deleting the organization and transferring or deleting projects.',+ Administrator:+ 'Manage members, billing, and project settings, including deleting projects. Cannot manage organization settings or owners.',+ Developer:+ 'Manage project content, including deleting data, users, files, and Edge Functions. Cannot change settings or delete projects.',+ 'Read-only':+ 'View resources without modifying or deleting them. SQL Editor access is limited to SELECT queries.',+}diff --git a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.network.test.tsx b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.network.test.tsxnew file mode 100644index 00000000000..c8138d6dc59--- /dev/null+++ b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.network.test.tsx@@ -0,0 +1,261 @@+import { fireEvent, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { platformComponents as components } from 'api-types'+import { HttpResponse } from 'msw'+import { beforeEach, describe, expect, test, vi } from 'vitest'++import { InviteMemberButton } from '@/components/interfaces/Organization/TeamSettings/InviteMemberButton'+import type { ProfileContextType } from '@/lib/profile'+import { createMockOrganizationResponse } from '@/tests/helpers'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'++type OrganizationResponse = components['schemas']['OrganizationResponse']+type Member = components['schemas']['Member']+type InvitationResponse = components['schemas']['InvitationResponse']+type OrganizationRoleResponse = components['schemas']['OrganizationRoleResponse']+type ListEntitlementsResponse = components['schemas']['ListEntitlementsResponse']+type CreateInvitationResponse = components['schemas']['CreateInvitationResponse']+type AccessControlPermission = components['schemas']['AccessControlPermission']++const ORG_SLUG = 'test-org'++const ROLE_IDS = { owner: 1, administrator: 2, developer: 3, readOnly: 4 } as const++vi.mock('common', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof import('common')+ return {+ ...actual,+ useParams: () => ({ slug: ORG_SLUG }),+ useIsLoggedIn: () => true,+ }+})++vi.mock('@/lib/constants', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>()+ return { ...actual, IS_PLATFORM: true }+})++const PROFILE_CONTEXT: ProfileContextType = {+ profile: {+ id: 1,+ auth0_id: 'auth0|test',+ gotrue_id: 'gotrue-test',+ username: 'testuser',+ primary_email: '[email protected]',+ first_name: null,+ last_name: null,+ mobile: null,+ is_alpha_user: false,+ is_sso_user: false,+ disabled_features: [],+ free_project_limit: null,+ },+ error: null,+ isLoading: false,+ isError: false,+ isSuccess: true,+}++const buildRole = (id: number, name: string): OrganizationRoleResponse['org_scoped_roles'][0] => ({+ id,+ name,+ base_role_id: id,+ description: null,+ projects: [],+})++const buildMember = (overrides: Partial<Member>): Member => ({+ gotrue_id: 'gotrue-test',+ is_sso_user: false,+ metadata: {},+ mfa_enabled: false,+ primary_email: '[email protected]',+ role_ids: [ROLE_IDS.developer],+ username: 'testuser',+ ...overrides,+})++const buildPermission = (resource: string): AccessControlPermission => ({+ actions: ['write:Create', 'write:Delete'],+ condition: null,+ organization_id: 1,+ organization_slug: ORG_SLUG,+ project_ids: [],+ project_refs: [],+ resources: [resource],+ restrictive: false,+})++function setupMocks(members: Member[] = [buildMember({})]) {+ const invitePayloads: unknown[] = []++ addAPIMock({+ method: 'get',+ path: '/platform/organizations',+ response: () =>+ HttpResponse.json<OrganizationResponse[]>([+ createMockOrganizationResponse({ id: 1, slug: ORG_SLUG, name: 'Test Org' }),+ ]),+ })++ addAPIMock({+ method: 'get',+ path: '/platform/profile/permissions',+ response: () =>+ HttpResponse.json<AccessControlPermission[]>([+ buildPermission('user_invites'),+ buildPermission('auth.subject_roles'),+ ]),+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/members',+ response: () => HttpResponse.json<Member[]>(members),+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/members/invitations',+ response: () => HttpResponse.json<InvitationResponse>({ invitations: [] }),+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/roles',+ response: () =>+ HttpResponse.json<OrganizationRoleResponse>({+ org_scoped_roles: [+ buildRole(ROLE_IDS.owner, 'Owner'),+ buildRole(ROLE_IDS.administrator, 'Administrator'),+ buildRole(ROLE_IDS.developer, 'Developer'),+ buildRole(ROLE_IDS.readOnly, 'Read-only'),+ ],+ // Unused by this component's org-scoped flow, but required by the schema+ project_scoped_roles: [],+ }),+ })++ // 404 with this message is how the query layer detects "no SSO provider" and+ // resolves the config to null (see getOrgSSOConfig).+ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/sso',+ response: () =>+ HttpResponse.json<APIErrorBody>(+ { message: 'Failed to find an existing SSO Provider' },+ { status: 404 }+ ),+ })++ addAPIMock({+ method: 'get',+ path: '/platform/organizations/:slug/entitlements',+ response: () => HttpResponse.json<ListEntitlementsResponse>({ entitlements: [] }),+ })++ addAPIMock({+ method: 'post',+ path: '/platform/organizations/:slug/members/invitations',+ response: async ({ request }) => {+ invitePayloads.push(await request.json())+ return HttpResponse.json<CreateInvitationResponse>({+ succeeded: ['[email protected]'],+ failed: [],+ })+ },+ })++ return { invitePayloads }+}++async function openDialog() {+ await waitFor(() => expect(screen.getByRole('button', { name: /invite members/i })).toBeEnabled())+ await userEvent.click(screen.getByRole('button', { name: /invite members/i }))+ return screen.findByRole('dialog')+}++describe('InviteMemberButton (network)', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ test('renders each role with its permission description and a roles docs link', async () => {+ setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()++ // Every role is rendered as a selectable card+ expect(await screen.findByText('Administrator')).toBeInTheDocument()+ expect(screen.getByText('Owner')).toBeInTheDocument()+ expect(screen.getByText('Developer')).toBeInTheDocument()+ expect(screen.getByText('Read-only')).toBeInTheDocument()++ // The key safety message from the ticket: Administrator can delete projects+ expect(screen.getByText(/including deleting projects/i)).toBeInTheDocument()++ // Roles documentation is one click away (the ticket's other complaint)+ const docsLink = screen.getByRole('link', { name: /roles and permissions/i })+ expect(docsLink).toHaveAttribute(+ 'href',+ expect.stringContaining('/guides/platform/access-control')+ )+ })++ test('sends emails and the default Developer role_id in the request body', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()+ await screen.findByText('Developer')++ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {+ target: { value: '[email protected]' },+ })+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))++ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({+ emails: ['[email protected]'],+ role_id: ROLE_IDS.developer,+ })+ })++ test('sends the selected role_id when a different role is chosen', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()++ // Select the Administrator card via the new RadioGroupStacked+ await userEvent.click(await screen.findByText('Administrator'))++ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {+ target: { value: '[email protected]' },+ })+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))++ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({+ emails: ['[email protected]'],+ role_id: ROLE_IDS.administrator,+ })+ })++ test('lowercases and de-duplicates emails before sending', async () => {+ const { invitePayloads } = setupMocks()+ customRender(<InviteMemberButton />, { profileContext: PROFILE_CONTEXT })+ await openDialog()+ await screen.findByText('Developer')++ fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {+ })+ fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))++ await waitFor(() => expect(invitePayloads).toHaveLength(1))+ expect(invitePayloads[0]).toEqual({+ emails: ['[email protected]', '[email protected]'],+ role_id: ROLE_IDS.developer,+ })+ })+})diff --git a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsxindex 2420b822bef..3706aeea3a4 100644--- a/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx+++ b/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx@@ -53,7 +53,12 @@ vi.mock('@/data/organizations/organization-members-query', () => ({}))const mockRoles = {- org_scoped_roles: [{ id: 1, name: 'Developer', description: null }],+ org_scoped_roles: [+ { id: 4, name: 'Owner', description: null },+ { id: 3, name: 'Administrator', description: null },+ { id: 1, name: 'Developer', description: null },+ { id: 2, name: 'Read-only', description: null },+ ],}vi.mock('@/data/organization-members/organization-roles-query', () => ({useOrganizationRolesV2Query: () => ({ data: mockRoles, isSuccess: true }),@@ -72,7 +77,10 @@ vi.mock('@/hooks/misc/useCheckEntitlements', () => ({}))vi.mock('@/components/interfaces/Organization/TeamSettings/TeamSettings.utils', () => ({- useGetRolesManagementPermissions: () => ({ rolesAddable: [1], rolesRemovable: [1] }),+ useGetRolesManagementPermissions: () => ({+ rolesAddable: [1, 2, 3, 4],+ rolesRemovable: [1, 2, 3, 4],+ }),}))const mockInvite = vi.fn().mockResolvedValue({ succeeded: [], failed: [] })@@ -126,6 +134,37 @@ describe('InviteMemberButton', () => {expect(screen.getByText('Invite team members')).toBeInTheDocument()})+ it('renders a stacked radio option with permission guidance for each role', async () => {+ customRender(<InviteMemberButton />)+ await openDialog()++ expect(screen.getAllByRole('radio')).toHaveLength(4)+ expect(screen.getByRole('link', { name: 'roles and permissions' })).toHaveAttribute(+ 'href',+ 'https://supabase.com/docs/guides/platform/access-control'+ )+ expect(+ screen.getByText(+ 'Full access, including deleting the organization and transferring or deleting projects.'+ )+ ).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Manage members, billing, and project settings, including deleting projects. Cannot manage organization settings or owners.'+ )+ ).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Manage project content, including deleting data, users, files, and Edge Functions. Cannot change settings or delete projects.'+ )+ ).toBeInTheDocument()+ expect(+ screen.getByText(+ 'View resources without modifying or deleting them. SQL Editor access is limited to SELECT queries.'+ )+ ).toBeInTheDocument()+ })+it('calls the mutation with a single email in an array', async () => {customRender(<InviteMemberButton />)await submitForm('[email protected]')