The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): shared connect layout for organisation invites (#45774)
Danny White791fc7441255
diff --git a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsx b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsxindex dd4101c5e45..cb8fcc14995 100644--- a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsx+++ b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInvite.tsx@@ -1,21 +1,27 @@import { useIsLoggedIn, useParams } from 'common'-import { CheckSquare } from 'lucide-react'import Link from 'next/link'import { useRouter } from 'next/router'+import type { ReactNode } from 'react'import { toast } from 'sonner'-import { Button, cn } from 'ui'-import { Admonition, GenericSkeletonLoader } from 'ui-patterns'+import { Button, Card, CardContent } from 'ui'+import { Admonition, ShimmeringLoader } from 'ui-patterns'import { OrganizationInviteError } from './OrganizationInviteError'+import {+ InterstitialAccountRow,+ InterstitialLayout,+ SupabaseLogo,+} from '@/components/layouts/InterstitialLayout'import { useOrganizationAcceptInvitationMutation } from '@/data/organization-members/organization-invitation-accept-mutation'import { useOrganizationInvitationTokenQuery } from '@/data/organization-members/organization-invitation-token-query'import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'-import { useProfile } from '@/lib/profile'+import { useProfile, useProfileNameAndPicture } from '@/lib/profile'export const OrganizationInvite = () => {const router = useRouter()const isLoggedIn = useIsLoggedIn()const { profile, isLoading: isLoadingProfile } = useProfile()+ const { username, avatarUrl, primaryEmail } = useProfileNameAndPicture()const { slug, token } = useParams()const isSignUpEnabled = useIsFeatureEnabled('dashboard_auth:sign_up')@@ -31,18 +37,53 @@ export const OrganizationInvite = () => {{retry: false,refetchOnWindowFocus: false,- enabled: !!profile,+ enabled: !!profile && !!slug && !!token,})+ const inviteIsNoLongerValid =+ error?.code === 401 && error?.message.includes('Failed to retrieve organization')+ const inviteIsInvalid =+ (isSuccessInvitation && !!data?.token_does_not_exist) ||+ (isErrorInvitation && error?.code === 404)const hasError =isErrorInvitation ||(isSuccessInvitation && (data.token_does_not_exist || data.expired_token || !data.email_match))- const inviteIsNoLongerValid =- error?.code === 401 && error?.message.includes('Failed to retrieve organization')- const organizationName = isSuccessInvitation ? data?.organization_name : 'An organization'+ const isWrongAccount = isSuccessInvitation && !!data && !data.email_match+ const showOrganizationHeader =+ isSuccessInvitation &&+ !!data &&+ !data.token_does_not_exist &&+ !data.expired_token &&+ !isWrongAccount+ const organizationName = data?.organization_name ?? 'an organization'+ const isSignedOut = !isLoggedIn || (!profile && !isLoadingProfile)+ const isInvitationLoading =+ !isSignedOut && (isLoadingProfile || isLoadingInvitation || !router.isReady)const loginRedirectLink = `/sign-in?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`const signupRedirectLink = `/sign-up?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`+ const interstitialTitle = inviteIsNoLongerValid+ ? 'Invite no longer available'+ : isSignedOut+ ? 'View invitation'+ : isWrongAccount+ ? 'Wrong account'+ : inviteIsInvalid+ ? 'Invite invalid'+ : isErrorInvitation+ ? 'Unable to load invitation'+ : data?.expired_token+ ? 'Invite expired'+ : showOrganizationHeader+ ? `Join ${organizationName}`+ : undefined+ const interstitialDescription = showOrganizationHeader+ ? isSignedOut+ ? `Sign in${isSignUpEnabled ? ' or create an account' : ''} to view this invitation`+ : 'You have been invited to join this Supabase organization'+ : isSignedOut+ ? `Sign in${isSignUpEnabled ? ' or create an account' : ''} to view this invitation`+ : undefinedconst { mutate: joinOrganization, isPending: isJoining } =useOrganizationAcceptInvitationMutation({@@ -60,92 +101,107 @@ export const OrganizationInvite = () => {joinOrganization({ slug, token })}- return (- <div- className={cn(- 'mx-auto overflow-hidden rounded-md border',- 'border-muted bg-alternative text-center shadow-sm',- 'md:w-[400px]'- )}+ const withLayout = (children: ReactNode) => (+ <InterstitialLayout+ logo={<SupabaseLogo />}+ title={+ isInvitationLoading ? (+ <ShimmeringLoader className="mx-auto h-7 w-36 max-w-full py-0" />+ ) : interstitialTitle ? (+ interstitialTitle+ ) : undefined+ }+ description={+ isInvitationLoading ? (+ <ShimmeringLoader className="mx-auto h-4 w-48 max-w-full py-0" />+ ) : interstitialDescription ? (+ interstitialDescription+ ) : undefined+ }+ titleClassName="text-xl">- {!isLoggedIn || (!profile && !isLoadingProfile) ? (- <>- <Admonition- showIcon={false}- type="default"- title={`Sign in${isSignUpEnabled ? ' or create an account' : ''} first to view this invitation`}- className="border-0 rounded-none text-left"- />- <div className="p-4 border-muted border-t flex gap-x-3 justify-center">- <Button asChild type="default">- <Link href={loginRedirectLink}>Sign in</Link>- </Button>- {isSignUpEnabled && (- <Button asChild type="default">- <Link href={signupRedirectLink}>Create an account</Link>- </Button>- )}- </div>- </>- ) : isLoadingProfile || isLoadingInvitation ? (- <div className="p-5">- <GenericSkeletonLoader />- </div>- ) : inviteIsNoLongerValid ? (- <>- <Admonition- type="default"- title="Invalid invitation"- description="This organization invite is no longer valid as it has either been accepted or declined"- className="border-0 rounded-none text-left"- />- <div className="p-4 border-muted border-t">- <Button type="default" asChild>- <Link href="/">Back to dashboard</Link>- </Button>- </div>- </>- ) : (- <>- <div className="flex flex-col gap-y-1 px-6 py-6">- <p className="text-sm text-foreground-light">You have been invited to join </p>- <p className="text-foreground text-2xl">{organizationName}</p>- {isSuccessInvitation && (- <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',- !isLoadingInvitation && !hasError && 'px-6 py-4'- )}- >- {hasError && (- <OrganizationInviteError data={data} error={error} isError={isErrorInvitation} />- )}- {isSuccessInvitation && !hasError && (- <div className="flex flex-row items-center justify-center gap-3">- <Button type="default" disabled={isJoining} asChild>- <Link href="/projects">Decline</Link>- </Button>- <Button- type="primary"- loading={isJoining}- disabled={isJoining}- onClick={handleJoinOrganization}- icon={<CheckSquare />}- >- Join organization- </Button>- </div>- )}+ <div className="px-6 pb-6">{children}</div>+ </InterstitialLayout>+ )++ if (isSignedOut) {+ return withLayout(+ <div className="flex flex-col gap-2">+ <Button asChild type="primary" block>+ <Link href={loginRedirectLink}>Sign in</Link>+ </Button>+ {isSignUpEnabled && (+ <Button asChild type="default" block>+ <Link href={signupRedirectLink}>Create an account</Link>+ </Button>+ )}+ </div>+ )+ }++ if (isInvitationLoading) {+ return withLayout(+ <div className="flex flex-col gap-6">+ <Card className="shadow-none">+ <CardContent className="flex items-center gap-3 border-none px-4 py-3">+ <ShimmeringLoader className="size-8 flex-shrink-0 rounded-full py-0" />+ <div className="min-w-0 flex-1 space-y-2">+ <ShimmeringLoader className="h-3 w-20 py-0" />+ <ShimmeringLoader className="h-4 w-40 max-w-full py-0" /></div>- </div>- </>- )}+ </CardContent>+ </Card>+ <div className="flex flex-col gap-2">+ <ShimmeringLoader className="h-10 w-full py-0" />+ <ShimmeringLoader className="h-10 w-full py-0" />+ </div>+ </div>+ )+ }++ if (inviteIsNoLongerValid) {+ return withLayout(+ <div className="flex flex-col gap-3">+ <Admonition+ type="warning"+ description="This invite has already been accepted or declined."+ />+ <Button type="default" block asChild>+ <Link href="/">Back to dashboard</Link>+ </Button>+ </div>+ )+ }++ if (hasError) {+ return withLayout(+ <OrganizationInviteError+ data={data}+ error={error}+ isError={isErrorInvitation}+ isInvalidInvite={inviteIsInvalid}+ />+ )+ }++ return withLayout(+ <div className="flex flex-col gap-6">+ <InterstitialAccountRow avatarUrl={avatarUrl} displayName={primaryEmail ?? username ?? ''} />++ <div className="flex flex-col gap-2">+ <Button+ type="primary"+ block+ loading={isJoining}+ disabled={isJoining}+ onClick={handleJoinOrganization}+ >+ Accept invite+ </Button>+ <Button asChild type="text" block>+ <Link href="/projects">Decline</Link>+ </Button>+ </div></div>)}diff --git a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsx b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsxindex c4c7b1c699c..e009e3789b7 100644--- a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsx+++ b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteError.tsx@@ -1,7 +1,7 @@import { useRouter } from 'next/router'-import { cn } from 'ui'+import { Button } from 'ui'+import { Admonition } from 'ui-patterns'-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'@@ -11,58 +11,79 @@ interface OrganizationInviteError {data?: OrganizationInviteByTokenerror?: ResponseError | nullisError: boolean+ isInvalidInvite?: boolean}-export const OrganizationInviteError = ({ data, error, isError }: OrganizationInviteError) => {+export const OrganizationInviteError = ({+ data,+ error,+ isError,+ isInvalidInvite,+}: OrganizationInviteError) => {const router = useRouter()const signOut = useSignOut()const { profile } = useProfile()- return (- <div className={cn('flex flex-col items-center justify-center gap-y-1 text-sm')}>- {isError ? (- <AlertError- error={error}- subject="Failed to retrieve token"- className="border-0 rounded-b [&>h5]:text-left [&>div]:items-start rounded-t-none"+ const handleSignOut = async () => {+ await signOut()+ router.reload()+ }++ if (isInvalidInvite) {+ return (+ <Admonition+ type="warning"+ description="Open the full invite link again, or ask the organization owner for a new invite."+ />+ )+ }++ if (isError) {+ return (+ <Admonition+ type="danger"+ description={error?.message ?? 'Open the full invite link again, or ask for a new invite.'}+ />+ )+ }++ if (!data?.email_match) {+ return (+ <div className="flex flex-col gap-3">+ <Admonition+ type="warning"+ description={+ profile?.primary_email ? (+ <>+ You are signed in as{' '}+ <span className="font-medium text-foreground">{profile.primary_email}</span>. Sign+ in with the email address that received this invite.+ </>+ ) : (+ 'Sign in with the email address that received this invite.'+ )+ }/>- ) : !data?.email_match ? (- <div className="p-4 flex flex-col gap-y-1">- <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>- </div>- ) : data.expired_token ? (- <div className="p-4 flex flex-col gap-y-1">- <p>The invite token has expired.</p>- <p className="text-foreground-lighter">- Please request a new one from the organization owner.- </p>- </div>- ) : (- <div className="p-4 flex flex-col gap-y-1">- <p>The invite token is invalid.</p>- <p className="text-foreground-lighter">- You could be logged in with the wrong account. Try copying and pasting the link from the- invite email, or ask the organization owner to invite you again.- </p>- </div>- )}- </div>+ <Button type="default" block onClick={handleSignOut}>+ Sign out+ </Button>+ </div>+ )+ }++ if (data.expired_token) {+ return (+ <Admonition+ type="warning"+ description="Ask the organization owner to send you a new invite."+ />+ )+ }++ return (+ <Admonition+ type="warning"+ description="Open the full invite link again, or ask the organization owner for a new invite."+ />)}diff --git a/apps/studio/components/layouts/InterstitialLayout.tsx b/apps/studio/components/layouts/InterstitialLayout.tsxnew file mode 100644index 00000000000..cd25002cfa0--- /dev/null+++ b/apps/studio/components/layouts/InterstitialLayout.tsx@@ -0,0 +1,119 @@+import { motion } from 'framer-motion'+import type { PropsWithChildren, ReactNode } from 'react'+import { Card, CardContent, CardHeader, cn } from 'ui'++import { ProfileImage } from '@/components/ui/ProfileImage'+import { BASE_PATH } from '@/lib/constants'++const MotionCard = motion.create(Card)++interface InterstitialLayoutProps {+ logo?: ReactNode+ title?: ReactNode+ description?: ReactNode+ containerClassName?: string+ cardClassName?: string+ titleClassName?: string+ descriptionClassName?: string+}++export const InterstitialLayout = ({+ logo,+ title,+ description,+ containerClassName,+ cardClassName,+ titleClassName,+ descriptionClassName,+ children,+}: PropsWithChildren<InterstitialLayoutProps>) => {+ const TitleElement = typeof title === 'string' ? 'h1' : 'div'+ const DescriptionElement = typeof description === 'string' ? 'p' : 'div'++ return (+ <div+ className={cn(+ 'flex min-h-screen w-full items-center justify-center bg-studio px-2 py-6',+ containerClassName+ )}+ >+ <MotionCard+ layout="size"+ transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}+ className={cn('mx-auto w-full max-w-[400px] overflow-hidden', cardClassName)}+ >+ {(logo || title || description) && (+ <CardHeader className="items-center gap-0 space-y-0 border-0 px-6 py-6 text-center font-normal [--card-padding-x:1.5rem]">+ {logo && <div className="mb-4 flex justify-center">{logo}</div>}+ {(title || description) && (+ <div className="flex flex-col items-center gap-1">+ {title && (+ <TitleElement+ className={cn(+ 'font-sans text-lg font-medium tracking-tight text-balance text-foreground',+ titleClassName+ )}+ >+ {title}+ </TitleElement>+ )}+ {description && (+ <DescriptionElement+ className={cn(+ '!m-0 px-3 text-sm leading-tight !text-balance text-foreground-lighter',+ descriptionClassName+ )}+ >+ {description}+ </DescriptionElement>+ )}+ </div>+ )}+ </CardHeader>+ )}+ {children}+ </MotionCard>+ </div>+ )+}++export const LogoBox = ({ children, className }: { children: ReactNode; className?: string }) => (+ <div+ className={cn(+ 'flex size-12 items-center justify-center overflow-hidden rounded-xl border bg-muted',+ className+ )}+ >+ {children}+ </div>+)++export const SupabaseLogo = () => (+ <LogoBox>+ <img alt="Supabase" src={`${BASE_PATH}/img/supabase-logo.svg`} className="size-7" />+ </LogoBox>+)++export const InterstitialAccountRow = ({+ avatarUrl,+ displayName,+}: {+ avatarUrl?: string+ displayName?: string+}) => (+ <Card className="border-muted bg-surface-200/50 shadow-none">+ <CardContent className="flex items-start gap-3 border-none p-3">+ <ProfileImage+ src={avatarUrl}+ alt={displayName}+ className="size-8 flex-shrink-0 rounded-full border border-muted"+ />+ <div className="min-w-0 flex-1">+ <p className="text-xs text-foreground-light">Signed in as</p>+ <p className="truncate text-sm text-foreground">+ {displayName || <span className="invisible">Loading account</span>}+ </p>+ </div>+ </CardContent>+ </Card>+)diff --git a/apps/studio/pages/join.tsx b/apps/studio/pages/join.tsxindex cb63ecd6f5f..21c07dddd7c 100644--- a/apps/studio/pages/join.tsx+++ b/apps/studio/pages/join.tsx@@ -1,48 +1,20 @@-import { useTheme } from 'next-themes'-import Link from 'next/link'-import { useEffect, useMemo, useState } from 'react'-import { cn } from 'ui'+import Head from 'next/head'import { OrganizationInvite } from '@/components/interfaces/OrganizationInvite/OrganizationInvite'-import { BASE_PATH } from '@/lib/constants'+import { buildStudioPageTitle } from '@/lib/page-title'import type { NextPageWithLayout } from '@/types'-const JoinOrganizationPage: NextPageWithLayout = () => {- const { resolvedTheme } = useTheme()- const isDarkMode = resolvedTheme?.includes('dark')-- const [mounted, setMounted] = useState(false)-- const imgUrl = useMemo(- () =>- isDarkMode ? `${BASE_PATH}/img/supabase-dark.svg` : `${BASE_PATH}/img/supabase-light.svg`,- [isDarkMode]- )-- useEffect(() => setMounted(true), [])+const PAGE_TITLE = buildStudioPageTitle({ section: 'Join Organization', brand: 'Supabase' })+const JoinOrganizationPage: NextPageWithLayout = () => {return (<>- <Link href="/projects" className="flex items-center justify-center gap-4">- {mounted && (- <img src={imgUrl} alt="Supabase" className="block h-[24px] cursor-pointer rounded-sm" />- )}- </Link>+ <Head>+ <title>{PAGE_TITLE}</title>+ </Head><OrganizationInvite /></>)}-JoinOrganizationPage.getLayout = (page) => (- <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'- )}- >- {page}- </div>-)-export default JoinOrganizationPagediff --git a/apps/studio/tests/components/OrganizationInvite.test.tsx b/apps/studio/tests/components/OrganizationInvite.test.tsxnew file mode 100644index 00000000000..6f05b49c978--- /dev/null+++ b/apps/studio/tests/components/OrganizationInvite.test.tsx@@ -0,0 +1,283 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, test, vi } from 'vitest'++import { OrganizationInvite } from '@/components/interfaces/OrganizationInvite/OrganizationInvite'+import type { OrganizationInviteByToken } from '@/data/organization-members/organization-invitation-token-query'+import type { ProfileContextType } from '@/lib/profile'+import { render } from '@/tests/helpers'+import type { ResponseError } from '@/types'++const mocks = vi.hoisted(() => ({+ isLoggedIn: vi.fn(),+ useParams: vi.fn(),+ useProfile: vi.fn(),+ useProfileNameAndPicture: vi.fn(),+ useIsFeatureEnabled: vi.fn(),+ useInvitationQuery: vi.fn(),+ useAcceptInvitationMutation: vi.fn(),+ acceptInvitation: vi.fn(),+ signOut: vi.fn(),+ routerPush: vi.fn(),+ routerReload: vi.fn(),+}))++vi.mock('common', async (importOriginal) => {+ const actual = (await importOriginal()) as typeof import('common')+ return {+ ...actual,+ useIsLoggedIn: mocks.isLoggedIn,+ useParams: mocks.useParams,+ }+})++vi.mock('next/router', () => ({+ useRouter: () => ({+ isReady: true,+ push: mocks.routerPush,+ reload: mocks.routerReload,+ }),+}))++vi.mock('@/lib/profile', () => ({+ useProfile: mocks.useProfile,+ useProfileNameAndPicture: mocks.useProfileNameAndPicture,+}))++vi.mock('@/lib/auth', () => ({+ useSignOut: () => mocks.signOut,+}))++vi.mock('@/hooks/misc/useIsFeatureEnabled', () => ({+ useIsFeatureEnabled: mocks.useIsFeatureEnabled,+}))++vi.mock('@/data/organization-members/organization-invitation-token-query', () => ({+ useOrganizationInvitationTokenQuery: mocks.useInvitationQuery,+}))++vi.mock('@/data/organization-members/organization-invitation-accept-mutation', () => ({+ useOrganizationAcceptInvitationMutation: mocks.useAcceptInvitationMutation,+}))++const READY_INVITE: OrganizationInviteByToken = {+ authorized_user: true,+ email_match: true,+ expired_token: false,+ invite_id: 42,+ organization_name: 'Acme Corp',+ sso_mismatch: false,+ token_does_not_exist: false,+}++const PROFILE: ProfileContextType['profile'] = {+ id: 1,+ auth0_id: 'auth0|test',+ gotrue_id: 'gotrue-test',+ username: 'jane',+ 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,+}++const responseError = (message: string, code = 500) => ({ message, code }) as ResponseError++function setSignedInDefaults() {+ mocks.isLoggedIn.mockReturnValue(true)+ mocks.useParams.mockReturnValue({ slug: 'acme-corp', token: 'invite-token' })+ mocks.useProfile.mockReturnValue({+ profile: PROFILE,+ isLoading: false,+ })+ mocks.useProfileNameAndPicture.mockReturnValue({+ username: 'jane',+ primaryEmail: '[email protected]',+ avatarUrl: undefined,+ isLoading: false,+ })+ mocks.useIsFeatureEnabled.mockReturnValue(true)+ mocks.useInvitationQuery.mockReturnValue({+ data: READY_INVITE,+ error: null,+ isSuccess: true,+ isError: false,+ isPending: false,+ })+ mocks.useAcceptInvitationMutation.mockReturnValue({+ mutate: mocks.acceptInvitation,+ isPending: false,+ })+}++describe('OrganizationInvite', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ setSignedInDefaults()+ })++ test('renders sign-in actions for signed-out users', () => {+ mocks.isLoggedIn.mockReturnValue(false)+ mocks.useProfile.mockReturnValue({ profile: null, isLoading: true })+ mocks.useProfileNameAndPicture.mockReturnValue({+ username: undefined,+ primaryEmail: undefined,+ avatarUrl: undefined,+ isLoading: false,+ })++ render(<OrganizationInvite />)++ expect(screen.getByText('View invitation')).toBeInTheDocument()+ expect(+ screen.getByText('Sign in or create an account to view this invitation')+ ).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Sign in' })).toHaveAttribute(+ 'href',+ '/sign-in?returnTo=%2Fjoin%3Ftoken%3Dinvite-token%26slug%3Dacme-corp'+ )+ expect(screen.getByRole('link', { name: 'Create an account' })).toHaveAttribute(+ 'href',+ '/sign-up?returnTo=%2Fjoin%3Ftoken%3Dinvite-token%26slug%3Dacme-corp'+ )+ })++ test('renders a ready invite for the signed-in account', () => {+ render(<OrganizationInvite />)++ expect(screen.getByText('Join Acme Corp')).toBeInTheDocument()+ expect(+ screen.getByText('You have been invited to join this Supabase organization')+ ).toBeInTheDocument()+ expect(screen.getByText('Signed in as')).toBeInTheDocument()+ expect(screen.getByText('[email protected]')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Accept invite' })).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Decline' })).toHaveAttribute('href', '/projects')+ })++ test('accepts an invite with the current slug and token', async () => {+ const user = userEvent.setup()++ render(<OrganizationInvite />)++ await user.click(screen.getByRole('button', { name: 'Accept invite' }))++ expect(mocks.acceptInvitation).toHaveBeenCalledWith({+ slug: 'acme-corp',+ token: 'invite-token',+ })+ })++ test('renders a wrong-account warning and signs out', async () => {+ const user = userEvent.setup()+ mocks.useInvitationQuery.mockReturnValue({+ data: { ...READY_INVITE, email_match: false },+ error: null,+ isSuccess: true,+ isError: false,+ isPending: false,+ })+ mocks.signOut.mockResolvedValue(undefined)++ render(<OrganizationInvite />)++ expect(screen.getByText('Wrong account')).toBeInTheDocument()+ expect(screen.queryByText('Join Acme Corp')).not.toBeInTheDocument()+ expect(+ screen.queryByText('You have been invited to join this Supabase organization')+ ).not.toBeInTheDocument()+ expect(screen.getByText(/jane@acmecorp\.io/)).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'Sign out' }))++ await waitFor(() => expect(mocks.signOut).toHaveBeenCalled())+ expect(mocks.routerReload).toHaveBeenCalled()+ })++ test('renders expired and invalid invite states', () => {+ mocks.useInvitationQuery.mockReturnValueOnce({+ data: { ...READY_INVITE, expired_token: true },+ error: null,+ isSuccess: true,+ isError: false,+ isPending: false,+ })++ const { rerender } = render(<OrganizationInvite />)++ expect(screen.getByText('Invite expired')).toBeInTheDocument()+ expect(+ screen.getByText('Ask the organization owner to send you a new invite.')+ ).toBeInTheDocument()++ mocks.useInvitationQuery.mockReturnValueOnce({+ data: { ...READY_INVITE, token_does_not_exist: true },+ error: null,+ isSuccess: true,+ isError: false,+ isPending: false,+ })++ rerender(<OrganizationInvite />)++ expect(screen.getByText('Invite invalid')).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Open the full invite link again, or ask the organization owner for a new invite.'+ )+ ).toBeInTheDocument()+ })++ test('renders no-longer-valid, invalid lookup, and generic error states', () => {+ mocks.useInvitationQuery.mockReturnValueOnce({+ data: undefined,+ error: responseError('Failed to retrieve organization', 401),+ isSuccess: false,+ isError: true,+ isPending: false,+ })++ const { rerender } = render(<OrganizationInvite />)++ expect(screen.getByText('Invite no longer available')).toBeInTheDocument()+ expect(+ screen.getByText('This invite has already been accepted or declined.')+ ).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Back to dashboard' })).toHaveAttribute('href', '/')++ mocks.useInvitationQuery.mockReturnValueOnce({+ data: undefined,+ error: responseError('Not Found', 404),+ isSuccess: false,+ isError: true,+ isPending: false,+ })++ rerender(<OrganizationInvite />)++ expect(screen.getByText('Invite invalid')).toBeInTheDocument()+ expect(+ screen.getByText(+ 'Open the full invite link again, or ask the organization owner for a new invite.'+ )+ ).toBeInTheDocument()+ expect(screen.queryByText('Not Found')).not.toBeInTheDocument()++ mocks.useInvitationQuery.mockReturnValueOnce({+ data: undefined,+ error: responseError('Failed to retrieve token', 500),+ isSuccess: false,+ isError: true,+ isPending: false,+ })++ rerender(<OrganizationInvite />)++ expect(screen.getByText('Unable to load invitation')).toBeInTheDocument()+ expect(screen.getByText('Failed to retrieve token')).toBeInTheDocument()+ })+})