The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): move AWS Marketplace to connect interstitial (#46058)
Danny Whitea8720dee1f6a
diff --git a/apps/studio/components/interfaces/Connect/OrganizationSelector.tsx b/apps/studio/components/interfaces/Connect/OrganizationSelector.tsxindex 7d2a98f7216..8e989dfaa92 100644--- a/apps/studio/components/interfaces/Connect/OrganizationSelector.tsx+++ b/apps/studio/components/interfaces/Connect/OrganizationSelector.tsx@@ -11,27 +11,39 @@ import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'import type { Organization } from '@/types'const VISIBLE_ORGANIZATIONS_LIMIT = 3-const CONNECT_DISCLOSURE_TRIGGER_CLASSNAME =- 'mx-auto flex h-7 cursor-pointer items-center justify-center gap-1.5 rounded-md px-2 text-xs text-foreground-lighter transition-colors hover:bg-surface-200 hover:text-foreground'+const CONNECT_DISCLOSURE_TRIGGER_CLASSNAME = cn(+ 'mx-auto flex h-7 cursor-pointer items-center justify-center gap-1.5 rounded-md px-2',+ 'text-xs text-foreground-lighter transition-colors',+ 'hover:bg-surface-200 hover:text-foreground',+ '[&[data-state=open]>svg]:-rotate-180!'+)export const OrganizationSelector = ({organizations,+ unavailableOrganizations = [],selectedSlug,disabled = false,description,createLabel,createHrefParams,+ onCreate,onSelect,getOrganizationDescription,+ getUnavailableOrganizationDescription,+ unavailableReason,}: {organizations: Organization[]+ unavailableOrganizations?: Organization[]selectedSlug?: string | nulldisabled?: booleandescription?: ReactNodecreateLabel?: stringcreateHrefParams?: { [key: string]: string }+ onCreate?: () => voidonSelect: (slug: string) => voidgetOrganizationDescription?: (organization: Organization) => ReactNode+ getUnavailableOrganizationDescription?: (organization: Organization) => ReactNode+ unavailableReason?: ReactNode}) => {const [showMore, setShowMore] = useState(false)const [lastVisitedOrganization] = useLocalStorageQuery(@@ -77,6 +89,7 @@ export const OrganizationSelector = ({}, [lastVisitedOrganization, organizations, selectedSlug])const hasOverflow = overflowOrganizations.length > 0+ const hasUnavailableOrganizations = unavailableOrganizations.length > 0return (<section className="space-y-2" aria-label="Organizations">@@ -100,17 +113,20 @@ export const OrganizationSelector = ({/>))}- {!!createLabel && !!createHrefParams && (- <CreateOrganizationCard params={createHrefParams} label={createLabel} />+ {!!createLabel && (!!createHrefParams || !!onCreate) && (+ <CreateOrganizationCard+ params={createHrefParams}+ label={createLabel}+ disabled={disabled}+ onClick={onCreate}+ />)}{hasOverflow && (<Collapsible open={showMore} onOpenChange={setShowMore}><CollapsibleTrigger className={CONNECT_DISCLOSURE_TRIGGER_CLASSNAME}><span>{showMore ? 'Show fewer' : `Show ${overflowOrganizations.length} more`}</span>- <ChevronDown- className={cn('size-3.5 transition-transform', showMore && 'rotate-180')}- />+ <ChevronDown className="size-3.5 transition-transform" /></CollapsibleTrigger><CollapsibleContent className="data-closed:animate-collapsible-up data-open:animate-collapsible-down overflow-hidden"><div className="space-y-2 pt-1">@@ -130,6 +146,35 @@ export const OrganizationSelector = ({</CollapsibleContent></Collapsible>)}++ {hasUnavailableOrganizations && (+ <Collapsible>+ <CollapsibleTrigger className={CONNECT_DISCLOSURE_TRIGGER_CLASSNAME}>+ <span>Organizations that can't be linked</span>+ <ChevronDown className="size-3.5 transition-transform" />+ </CollapsibleTrigger>+ <CollapsibleContent className="data-closed:animate-collapsible-up data-open:animate-collapsible-down overflow-hidden">+ <div className="space-y-2 pt-1">+ {unavailableOrganizations.map((organization) => (+ <ConnectOrganizationButton+ key={organization.slug}+ organization={organization}+ disabled+ description={+ getUnavailableOrganizationDescription?.(organization) ??+ getPlanDescription(organization)+ }+ />+ ))}+ {unavailableReason && (+ <p className="mx-auto max-w-xs text-center text-xs text-foreground-lighter text-balance">+ {unavailableReason}+ </p>+ )}+ </div>+ </CollapsibleContent>+ </Collapsible>+ )}</div></section>)diff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceContractNotLinkable.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceContractNotLinkable.tsxdeleted file mode 100644index a32ec0f946e..00000000000--- a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceContractNotLinkable.tsx+++ /dev/null@@ -1,81 +0,0 @@-import Link from 'next/link'-import { Button, Card, CardContent } from 'ui'--import { SupportLink } from '../../Support/SupportLink'-import { CloudMarketplaceContractLinkingIneligibilityReason } from './cloud-marketplace-query'--interface Props {- reason: CloudMarketplaceContractLinkingIneligibilityReason-}--const AwsMarketplaceContractNotLinkable = ({ reason }: Props) => {- return (- <div className="mt-5 mb-10">- <Card className="p-4">- <CardContent>{determineCardContent(reason)}</CardContent>- </Card>- </div>- )-}--function determineCardContent(reason: CloudMarketplaceContractLinkingIneligibilityReason) {- switch (reason) {- case 'NO_ACTIVE_CONTRACT_FOUND':- return (- <p>- Thanks for purchasing Supabase through the AWS Marketplace. It’ll take a moment for all- systems to sync before you can link your Supabase organization to the AWS Marketplace.- Please try again in a few minutes.- </p>- )-- case 'AWS_ACTIVATE_CREDITS_DEAL':- return (- <>- <p className="mb-4">- You’ve accepted a private offer for Supabase credits as part of AWS Activate. No further- action is required on your end.- </p>- <p>- Your Supabase organization’s credit balance will be updated accordingly. Please note- that it may take 1 or 2 days for this change to appear on the Dashboard. You can find- the credit balance on the{' '}- <Link className="underline" href={'/org/_/billing'}>- organization's billing page- </Link>- .- </p>-- <Button asChild type="primary" size="medium" className="mt-8">- <Link href="/organizations">Go to Dashboard</Link>- </Button>- </>- )-- case 'AGREEMENT_BASED_OFFER':- return (- <>- <p>- You’ve accepted a private offer that updated or extended an existing Supabase- subscription on the AWS Marketplace. No further action is required on your end. Your- Supabase organization will remain linked to the AWS Marketplace, and your projects will- continue to run as usual.- </p>-- <Button asChild type="primary" size="medium" className="mt-8">- <Link href="/organizations">Go to Dashboard</Link>- </Button>- </>- )-- default:- return (- <p>- Unable to determine the reason why AWS Marketplace onboarding is not possible.{' '}- <SupportLink className="underline">Contact support.</SupportLink>- </p>- )- }-}--export default AwsMarketplaceContractNotLinkablediff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceCreateNewOrg.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceCreateNewOrg.tsxdeleted file mode 100644index 723396ab11b..00000000000--- a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceCreateNewOrg.tsx+++ /dev/null@@ -1,103 +0,0 @@-import Link from 'next/link'-import { useRouter } from 'next/router'-import { SubmitHandler } from 'react-hook-form'-import { toast } from 'sonner'-import { Button } from 'ui'--import AwsMarketplaceAutoRenewalWarning from './AwsMarketplaceAutoRenewalWarning'-import AwsMarketplaceOnboardingPlaceholder from './AwsMarketplaceOnboardingPlaceholder'-import { useCloudMarketplaceOnboardingInfoQuery } from './cloud-marketplace-query'-import NewAwsMarketplaceOrgForm, {- CREATE_AWS_MANAGED_ORG_FORM_ID,- NewMarketplaceOrgForm,-} from './NewAwsMarketplaceOrgForm'-import {- ScaffoldSection,- ScaffoldSectionContent,- ScaffoldSectionDetail,-} from '@/components/layouts/Scaffold'-import { useAwsManagedOrganizationCreateMutation } from '@/data/organizations/organization-create-mutation'-import { DOCS_URL } from '@/lib/constants'--const AwsMarketplaceCreateNewOrg = () => {- const router = useRouter()- const {- query: { buyer_id: buyerId },- } = router-- const { data: onboardingInfo, isPending: isLoadingOnboardingInfo } =- useCloudMarketplaceOnboardingInfoQuery({- buyerId: buyerId as string,- })-- const { mutate: createOrganization, isPending: isCreatingOrganization } =- useAwsManagedOrganizationCreateMutation({- onSuccess: (org) => {- //TODO(thomas): send tracking event?- router.push(`/org/${org.slug}`)- },- onError: (res) => {- toast.error(res.message, {- duration: 7_000,- })- },- })-- const onSubmit: SubmitHandler<NewMarketplaceOrgForm> = async (values) => {- createOrganization({ ...values, buyerId: buyerId as string })- }-- return (- <>- {onboardingInfo &&- !onboardingInfo.aws_contract_auto_renewal &&- !onboardingInfo.aws_contract_is_private_offer && (- <AwsMarketplaceAutoRenewalWarning- awsContractEndDate={onboardingInfo.aws_contract_end_date}- awsContractSettingsUrl={onboardingInfo.aws_contract_settings_url}- />- )}- {isLoadingOnboardingInfo ? (- <AwsMarketplaceOnboardingPlaceholder />- ) : (- <ScaffoldSection>- <ScaffoldSectionDetail className="text-base">- <p>- You’ve subscribed to the Supabase {onboardingInfo?.plan_name_selected_on_marketplace}{' '}- Plan via the AWS Marketplace. As a final step, you need to create a Supabase- organization. That organization will be managed and billed through AWS Marketplace.- </p>- <p>- You can read more on billing through AWS in our {''}- <Link- href={`${DOCS_URL}/guides/platform/aws-marketplace`}- target="_blank"- className="underline"- >- Billing Docs.- </Link>- </p>- </ScaffoldSectionDetail>- <ScaffoldSectionContent className="lg:ml-10">- <div className="border-l px-10 pt-10">- <NewAwsMarketplaceOrgForm onSubmit={onSubmit} />-- <div className="flex justify-end mt-10">- <Button- form={CREATE_AWS_MANAGED_ORG_FORM_ID}- htmlType="submit"- loading={isCreatingOrganization}- size="medium"- >- Create organization- </Button>- </div>- </div>- </ScaffoldSectionContent>- </ScaffoldSection>- )}- </>- )-}--export default AwsMarketplaceCreateNewOrgdiff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceLinkExistingOrg.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceLinkExistingOrg.tsxdeleted file mode 100644index d388900bbdf..00000000000--- a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceLinkExistingOrg.tsx+++ /dev/null@@ -1,325 +0,0 @@-import { zodResolver } from '@hookform/resolvers/zod'-import { RadioGroupCard, RadioGroupCardItem } from '@ui/components/radio-group-card'-import { cn } from '@ui/lib/utils'-import { ChevronRight } from 'lucide-react'-import Link from 'next/link'-import { useRouter } from 'next/router'-import { useMemo, useState } from 'react'-import { SubmitHandler, useForm } from 'react-hook-form'-import { toast } from 'sonner'-import {- Button,- Collapsible,- CollapsibleContent,- CollapsibleTrigger,- Form,- FormField,- Skeleton,-} from 'ui'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'-import { z } from 'zod'--import { OrganizationCard } from '../OrganizationCard'-import AwsMarketplaceAutoRenewalWarning from './AwsMarketplaceAutoRenewalWarning'-import AwsMarketplaceOnboardingPlaceholder from './AwsMarketplaceOnboardingPlaceholder'-import AwsMarketplaceOnboardingSuccessModal from './AwsMarketplaceOnboardingSuccessModal'-import { useCloudMarketplaceOnboardingInfoQuery } from './cloud-marketplace-query'-import NewAwsMarketplaceOrgModal from './NewAwsMarketplaceOrgModal'-import {- ScaffoldSection,- ScaffoldSectionContent,- ScaffoldSectionDetail,-} from '@/components/layouts/Scaffold'-import { ButtonTooltip } from '@/components/ui/ButtonTooltip'-import { useOrganizationLinkAwsMarketplaceMutation } from '@/data/organizations/organization-link-aws-marketplace-mutation'-import { DOCS_URL } from '@/lib/constants'-import type { Organization } from '@/types'--interface AwsMarketplaceLinkExistingOrgProps {- organizations?: Organization[] | undefined-}--const FormSchema = z.object({- orgSlug: z.string(),-})--type LinkExistingOrgForm = z.infer<typeof FormSchema>--export const AwsMarketplaceLinkExistingOrg = ({- organizations,-}: AwsMarketplaceLinkExistingOrgProps) => {- const router = useRouter()- const {- query: { buyer_id: buyerId },- } = router-- const { data: onboardingInfo, isPending: isLoadingOnboardingInfo } =- useCloudMarketplaceOnboardingInfoQuery({- buyerId: buyerId as string,- })-- const form = useForm<LinkExistingOrgForm>({- resolver: zodResolver(FormSchema),- defaultValues: {- orgSlug: undefined,- },- mode: 'onBlur',- reValidateMode: 'onChange',- })-- const isDirty = !!Object.keys(form.formState.dirtyFields).length-- // Sort organizations by name ascending- const sortedOrganizations = useMemo(() => {- return organizations?.slice().sort((a, b) => a.name.localeCompare(b.name))- }, [organizations])-- const { orgsLinkable, orgsNotLinkable } = useMemo(() => {- const orgQualifiesForLinking = (org: Organization) => {- const validationResult = onboardingInfo?.organization_linking_eligibility.find(- (result) => result.slug === org.slug- )-- return validationResult?.is_eligible ?? false- }-- const linkable: Organization[] = []- const notLinkable: Organization[] = []- sortedOrganizations?.forEach((org) => {- if (orgQualifiesForLinking(org)) {- linkable.push(org)- } else {- notLinkable.push(org)- }- })- return { orgsLinkable: linkable, orgsNotLinkable: notLinkable }- }, [sortedOrganizations, onboardingInfo?.organization_linking_eligibility])-- const [isNotLinkableOrgListOpen, setIsNotLinkableOrgListOpen] = useState(false)- const [orgLinkedSuccessfully, setOrgLinkedSuccessfully] = useState(false)- const [showOrgCreationDialog, setShowOrgCreationDialog] = useState(false)- const [orgToRedirectTo, setOrgToRedirectTo] = useState('')-- const { mutate: linkOrganization, isPending: isLinkingOrganization } =- useOrganizationLinkAwsMarketplaceMutation({- onSuccess: (_) => {- //TODO(thomas): send tracking event?- setOrgLinkedSuccessfully(true)- setOrgToRedirectTo(form.getValues('orgSlug'))- },- onError: (res) => {- toast.error(res.message, {- duration: 7_000,- })- },- })-- const onSubmit: SubmitHandler<LinkExistingOrgForm> = async (values) => {- linkOrganization({ slug: values.orgSlug, buyerId: buyerId as string })- }-- return (- <>- {onboardingInfo &&- !onboardingInfo.aws_contract_auto_renewal &&- !onboardingInfo.aws_contract_is_private_offer && (- <AwsMarketplaceAutoRenewalWarning- awsContractEndDate={onboardingInfo.aws_contract_end_date}- awsContractSettingsUrl={onboardingInfo.aws_contract_settings_url}- />- )}- {isLoadingOnboardingInfo ? (- <AwsMarketplaceOnboardingPlaceholder />- ) : (- <ScaffoldSection>- <ScaffoldSectionDetail className="text-base">- <>- <p>- You’ve subscribed to the Supabase{' '}- {onboardingInfo?.plan_name_selected_on_marketplace} Plan via the AWS Marketplace. As- a final step, you need to link a Supabase organization to that subscription. Select- the organization you want to be managed and billed through AWS.- </p>-- <p>- You can read more on billing through AWS in our {''}- <Link- href={`${DOCS_URL}/guides/platform/aws-marketplace`}- target="_blank"- className="underline"- >- Billing Docs.- </Link>- </p>-- <p className="mt-10">- <span className="font-bold text-foreground-light">Want to start fresh?</span> Create- a new organization and it will be linked automatically.- </p>- <Button- size="tiny"- htmlType="submit"- type="primary"- onClick={async (e) => {- e.preventDefault()- setShowOrgCreationDialog(true)- }}- >- Create organization- </Button>- </>- </ScaffoldSectionDetail>-- <ScaffoldSectionContent className="lg:ml-10">- <Form {...form}>- <form className="flex flex-col">- <FormField- name="orgSlug"- control={form.control}- render={({ field }) => (- <RadioGroupCard- {...field}- defaultValue={field.value}- onValueChange={(value: string) => {- form.setValue('orgSlug', value, {- shouldDirty: true,- shouldValidate: false,- })- }}- >- <FormItemLayout id={field.name}>- <div className={'grid gap-4 grid-cols-1'}>- {isLoadingOnboardingInfo ? (- Array(3)- .fill(0)- .map((_, i) => (- <Skeleton key={i} className="w-full h-[110px] rounded-md" />- ))- ) : (- <>- <p className="font-bold text-foreground-light">- Organizations that can be linked- </p>- {orgsLinkable.length === 0 ? (- <p className="text-sm text-foreground-light">- None of your organizations can be linked to your AWS Marketplace- subscription at the moment.- </p>- ) : (- orgsLinkable.map((org) => (- <RadioGroupCardItem- id={org.slug}- key={org.slug}- showIndicator={false}- value={org.slug}- className={cn(- 'relative text-sm text-left flex flex-col gap-0 p-0 [&_label]:w-full group w-full'- )}- label={- <OrganizationCard- key={org.id}- isLink={false}- organization={org}- />- }- />- ))- )}- </>- )}- </div>- </FormItemLayout>- </RadioGroupCard>- )}- />- </form>- </Form>-- {orgsNotLinkable.length > 0 && !isLoadingOnboardingInfo && (- <Collapsible- className="-space-y-px"- open={isNotLinkableOrgListOpen || orgsLinkable.length === 0}- onOpenChange={() => setIsNotLinkableOrgListOpen((prev) => !prev)}- >- <CollapsibleTrigger className="py-2 w-full flex items-center group justify-between">- <p className="text-xs font-bold text-foreground-light">- Organizations that can't be linked- </p>- <ChevronRight- size={16}- className="text-foreground-lighter transition-all group-data-open:rotate-90"- strokeWidth={1}- />- </CollapsibleTrigger>- <CollapsibleContent- className={cn(- 'flex flex-col gap-4 transition-all',- 'data-closed:animate-collapsible-up data-open:animate-collapsible-down'- )}- >- <p className="text-foreground-light text-xs">- The following organizations can’t be linked to your AWS Marketplace subscription- at the moment. This may be due to missing permissions, outstanding invoices, or- an existing marketplace link. If you'd like to link one of these organizations,- please review the organization settings. You need to be Owner or Administrator- of the organization to link it.- </p>- <div className="text-sm text-left flex flex-col gap-4 p-0 [&_label]:w-full group] w-full opacity-60">- {orgsNotLinkable.map((org) => (- <OrganizationCard- isLink={false}- key={org.id}- organization={org}- className="cursor-not-allowed"- />- ))}- </div>- </CollapsibleContent>- </Collapsible>- )}-- <div className={cn('flex gap-3 justify-end')}>- <ButtonTooltip- size="medium"- htmlType="submit"- type="primary"- onClick={async () => {- await onSubmit(form.getValues())- }}- loading={isLinkingOrganization}- disabled={!isDirty || isLinkingOrganization || isLoadingOnboardingInfo}- tooltip={{- content: {- side: 'top',- text: !isDirty ? 'No organization selected' : undefined,- },- }}- >- Link organization- </ButtonTooltip>- </div>- </ScaffoldSectionContent>- </ScaffoldSection>- )}-- <AwsMarketplaceOnboardingSuccessModal- visible={orgLinkedSuccessfully}- onClose={() => {- setOrgLinkedSuccessfully(false)- router.push(`/org/${orgToRedirectTo}`)- }}- />-- <NewAwsMarketplaceOrgModal- visible={showOrgCreationDialog}- onClose={() => setShowOrgCreationDialog(false)}- buyerId={buyerId as string}- onSuccess={(newlyCreatedOrgSlug) => {- setShowOrgCreationDialog(false)- setOrgToRedirectTo(newlyCreatedOrgSlug)- setOrgLinkedSuccessfully(true)- }}- />- </>- )-}diff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding.components.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding.components.tsxnew file mode 100644index 00000000000..0923335ca90--- /dev/null+++ b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding.components.tsx@@ -0,0 +1,139 @@+import { type ReactNode } from 'react'+import { Card, CardContent } from 'ui'+import { Admonition, ShimmeringLoader } from 'ui-patterns'++import type {+ CloudMarketplaceContractLinkingIneligibilityReason,+ CloudMarketplaceOnboardingInfo,+} from './cloud-marketplace-query'+import {+ InterstitialLayout,+ LogoBox,+ LogoPair,+ SupabaseLogo,+} from '@/components/layouts/InterstitialLayout'+import { BASE_PATH } from '@/lib/constants'++const INTERSTITIAL_TITLE = 'Link AWS Marketplace'+const INTERSTITIAL_DESCRIPTION = 'Choose an organization to bill through AWS'++const AwsLogo = () => (+ <LogoBox className="border-[#232f3e] dark:border-control bg-[#232f3e]">+ <img alt="AWS" src={`${BASE_PATH}/img/icons/aws-icon.svg`} className="w-8 mt-1" />+ </LogoBox>+)++export const AwsMarketplaceInterstitial = ({+ description,+ children,+}: {+ description?: ReactNode+ children: ReactNode+}) => (+ <InterstitialLayout+ logo={<LogoPair left={<AwsLogo />} right={<SupabaseLogo />} />}+ title={INTERSTITIAL_TITLE}+ description={description ?? INTERSTITIAL_DESCRIPTION}+ >+ <div className="px-6 pb-6">{children}</div>+ </InterstitialLayout>+)++export const ConnectLoadingCards = () => (+ <div className="flex flex-col gap-5">+ <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>+ </CardContent>+ </Card>+ <section className="space-y-2" aria-label="Organizations">+ <ShimmeringLoader className="h-3 w-24 py-0" />+ {Array.from({ length: 3 }).map((_, index) => (+ <Card key={index} className="shadow-none">+ <CardContent className="flex items-center gap-3 border-none px-4 py-3">+ <ShimmeringLoader className="size-9 flex-shrink-0 rounded-lg py-0" />+ <div className="min-w-0 flex-1 space-y-2">+ <ShimmeringLoader className="h-4 w-32 py-0" />+ <ShimmeringLoader className="h-3 w-20 py-0" />+ </div>+ </CardContent>+ </Card>+ ))}+ </section>+ <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>+)++export function getOrganizationUnavailableReason(+ reason:+ | CloudMarketplaceOnboardingInfo['organization_linking_eligibility'][number]['reasons'][number]+ | undefined+) {+ switch (reason) {+ case 'ALREADY_MANAGED_BY_PARTNER_AWS':+ return 'Already linked to AWS Marketplace'+ case 'ALREADY_MANAGED_BY_PARTNER':+ return 'Already managed by another partner'+ case 'OVERDUE_INVOICES':+ return 'Outstanding invoices'+ default:+ return 'Not available for marketplace billing'+ }+}++export function getContractIneligibilityDescription(+ reason: CloudMarketplaceContractLinkingIneligibilityReason | undefined+) {+ switch (reason) {+ case 'AWS_ACTIVATE_CREDITS_DEAL':+ return 'No further action is required for this AWS Activate credits offer'+ case 'AGREEMENT_BASED_OFFER':+ return 'This private offer updated an existing AWS Marketplace subscription'+ case 'NO_ACTIVE_CONTRACT_FOUND':+ return 'AWS is still syncing this Marketplace subscription'+ default:+ return 'This AWS Marketplace subscription cannot be linked right now'+ }+}++export function ContractIneligibilityNotice({+ reason,+}: {+ reason: CloudMarketplaceContractLinkingIneligibilityReason | undefined+}) {+ switch (reason) {+ case 'AWS_ACTIVATE_CREDITS_DEAL':+ return (+ <Admonition+ type="success"+ title="Credits accepted"+ description="Your Supabase organization credit balance will be updated after AWS finishes processing the offer. This can take 1 or 2 days."+ />+ )+ case 'AGREEMENT_BASED_OFFER':+ return (+ <Admonition+ type="success"+ title="No action required"+ description="Your existing Supabase organization remains linked to AWS Marketplace and your projects will continue to run as usual."+ />+ )+ case 'NO_ACTIVE_CONTRACT_FOUND':+ return (+ <Admonition+ type="warning"+ title="Still syncing"+ description="Thanks for purchasing Supabase through AWS Marketplace. It can take a few minutes before the subscription is ready to link. Try again shortly."+ />+ )+ default:+ return <Admonition type="default" description="If the problem persists, contact support." />+ }+}diff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding.tsxnew file mode 100644index 00000000000..4393fe473aa--- /dev/null+++ b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding.tsx@@ -0,0 +1,326 @@+import Link from 'next/link'+import { useEffect, useMemo, useState } from 'react'+import { toast } from 'sonner'+import { Button } from 'ui'+import { Admonition, ShimmeringLoader } from 'ui-patterns'++import {+ AwsMarketplaceInterstitial,+ ConnectLoadingCards,+ ContractIneligibilityNotice,+ getContractIneligibilityDescription,+ getOrganizationUnavailableReason,+} from './AwsMarketplaceOnboarding.components'+import { OrganizationSelector } from '@/components/interfaces/Connect/OrganizationSelector'+import AwsMarketplaceAutoRenewalWarning from '@/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceAutoRenewalWarning'+import {+ useCloudMarketplaceContractLinkingEligibilityQuery,+ useCloudMarketplaceOnboardingInfoQuery,+ type CloudMarketplaceOnboardingInfo,+} from '@/components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query'+import NewAwsMarketplaceOrgModal from '@/components/interfaces/Organization/CloudMarketplace/NewAwsMarketplaceOrgModal'+import { InterstitialAccountRow } from '@/components/layouts/InterstitialLayout'+import { InlineLink } from '@/components/ui/InlineLink'+import { useOrganizationLinkAwsMarketplaceMutation } from '@/data/organizations/organization-link-aws-marketplace-mutation'+import { useOrganizationsQuery } from '@/data/organizations/organizations-query'+import { DOCS_URL } from '@/lib/constants'+import { useProfile } from '@/lib/profile'+import type { Organization } from '@/types'++const EMPTY_ORGANIZATIONS: Organization[] = []++export const AwsMarketplaceOnboardingScreen = ({ buyerId }: { buyerId?: string }) => {+ const { profile } = useProfile()++ const [selectedOrgSlug, setSelectedOrgSlug] = useState<string | null>(null)+ const [linkedOrgSlug, setLinkedOrgSlug] = useState<string | null>(null)+ const [showOrgCreationDialog, setShowOrgCreationDialog] = useState(false)++ useEffect(() => {+ setSelectedOrgSlug(null)+ setLinkedOrgSlug(null)+ setShowOrgCreationDialog(false)+ }, [buyerId])++ const {+ data: organizations,+ error: organizationsError,+ isPending: isLoadingOrganizations,+ isError: isOrganizationsError,+ } = useOrganizationsQuery({ enabled: !!buyerId })++ const {+ data: contractLinkingEligibility,+ error: eligibilityError,+ isPending: isLoadingEligibility,+ isError: isEligibilityError,+ } = useCloudMarketplaceContractLinkingEligibilityQuery(+ { buyerId: buyerId ?? '' },+ { enabled: !!buyerId }+ )++ const shouldLoadOnboardingInfo = !!buyerId && contractLinkingEligibility?.eligibility.is_eligible++ const {+ data: onboardingInfo,+ error: onboardingInfoError,+ isPending: isLoadingOnboardingInfo,+ isError: isOnboardingInfoError,+ } = useCloudMarketplaceOnboardingInfoQuery(+ { buyerId: buyerId ?? '' },+ { enabled: !!shouldLoadOnboardingInfo }+ )++ const { mutate: linkOrganization, isPending: isLinkingOrganization } =+ useOrganizationLinkAwsMarketplaceMutation({+ onSuccess: (_, variables) => {+ setLinkedOrgSlug(variables.slug)+ },+ onError: (error) => {+ toast.error(error.message, { duration: 7_000 })+ },+ })++ const effectiveOrganizations = useMemo(+ () => organizations ?? EMPTY_ORGANIZATIONS,+ [organizations]+ )+ const effectiveIsLoading =+ isLoadingOrganizations ||+ isLoadingEligibility ||+ (contractLinkingEligibility?.eligibility.is_eligible && isLoadingOnboardingInfo)+ const effectiveIsError = isOrganizationsError || isEligibilityError || isOnboardingInfoError+ const effectiveError = organizationsError ?? eligibilityError ?? onboardingInfoError+ const displayName = profile?.primary_email ?? profile?.username+ const selectedOrganization = effectiveOrganizations.find(({ slug }) => slug === selectedOrgSlug)+ const orgLinked = linkedOrgSlug !== null+ const linkedOrganization =+ effectiveOrganizations.find(({ slug }) => slug === linkedOrgSlug) ?? selectedOrganization++ const { linkableOrganizations, unavailableOrganizations, eligibilityByOrganizationSlug } =+ useMemo(() => {+ const sortedOrganizations = effectiveOrganizations+ .slice()+ .sort((a, b) => a.name.localeCompare(b.name))++ if (!onboardingInfo) {+ return {+ linkableOrganizations: [],+ unavailableOrganizations: sortedOrganizations,+ eligibilityByOrganizationSlug: new Map<+ string,+ CloudMarketplaceOnboardingInfo['organization_linking_eligibility'][number]+ >(),+ }+ }++ const eligibilityBySlug = new Map(+ onboardingInfo.organization_linking_eligibility.map((eligibility) => [+ eligibility.slug,+ eligibility,+ ])+ )++ const linkable: Organization[] = []+ const unavailable: Organization[] = []++ sortedOrganizations.forEach((organization) => {+ const organizationEligibility = eligibilityBySlug.get(organization.slug)++ if (organizationEligibility?.is_eligible) {+ linkable.push(organization)+ } else {+ unavailable.push(organization)+ }+ })++ return {+ linkableOrganizations: linkable,+ unavailableOrganizations: unavailable,+ eligibilityByOrganizationSlug: eligibilityBySlug,+ }+ }, [onboardingInfo, effectiveOrganizations])++ if (!buyerId) {+ return (+ <AwsMarketplaceInterstitial>+ <div className="flex flex-col gap-3">+ <Admonition+ type="warning"+ title="Setup unavailable"+ description={+ <p>+ Open the onboarding link from AWS Marketplace again. The link must include a{' '}+ <code className="text-code-inline">buyer_id</code> parameter.+ </p>+ }+ />+ <Button type="default" block asChild>+ <Link href="/organizations">Back to dashboard</Link>+ </Button>+ </div>+ </AwsMarketplaceInterstitial>+ )+ }++ if (effectiveIsLoading) {+ return (+ <AwsMarketplaceInterstitial+ description={<ShimmeringLoader className="mx-auto h-4 w-56 max-w-full py-0" />}+ >+ <ConnectLoadingCards />+ </AwsMarketplaceInterstitial>+ )+ }++ if (effectiveIsError) {+ return (+ <AwsMarketplaceInterstitial>+ <div className="flex flex-col gap-3">+ <Admonition+ type="warning"+ title="Unable to load setup"+ description={+ <>+ Please try again. If the problem persists, contact support.+ {effectiveError && (+ <span className="mt-1 block text-foreground-lighter">+ Error: {effectiveError.message}+ </span>+ )}+ </>+ }+ />+ <Button type="default" block asChild>+ <Link href="/organizations">Back to dashboard</Link>+ </Button>+ </div>+ </AwsMarketplaceInterstitial>+ )+ }++ if (!contractLinkingEligibility?.eligibility.is_eligible) {+ const reason = contractLinkingEligibility?.eligibility.reasons[0]++ return (+ <AwsMarketplaceInterstitial description={getContractIneligibilityDescription(reason)}>+ <div className="flex flex-col gap-3">+ <ContractIneligibilityNotice reason={reason} />+ <Button type="default" block asChild>+ <Link href="/organizations">Back to dashboard</Link>+ </Button>+ </div>+ </AwsMarketplaceInterstitial>+ )+ }++ if (orgLinked) {+ return (+ <AwsMarketplaceInterstitial>+ <div className="flex flex-col gap-3">+ <Admonition+ type="success"+ title="Organization linked"+ description={+ linkedOrganization+ ? `${linkedOrganization.name} will be billed through AWS Marketplace.`+ : 'The selected organization will be billed through AWS Marketplace.'+ }+ />+ <Button type="primary" block asChild>+ <Link href={`/org/${linkedOrganization?.slug ?? linkedOrgSlug}`}>+ Go to organization+ </Link>+ </Button>+ </div>+ </AwsMarketplaceInterstitial>+ )+ }++ const showAutoRenewalWarning =+ onboardingInfo &&+ !onboardingInfo.aws_contract_auto_renewal &&+ !onboardingInfo.aws_contract_is_private_offer+ const hasLinkableOrganizations = linkableOrganizations.length > 0+ const hasAnyOrganizations = effectiveOrganizations.length > 0+ const isLinking = isLinkingOrganization+ const primaryLabel = hasLinkableOrganizations ? 'Link organization' : 'Create organization'+ const primaryAction = hasLinkableOrganizations+ ? () => {+ if (!selectedOrgSlug || !buyerId) return+ linkOrganization({ slug: selectedOrgSlug, buyerId })+ }+ : () => setShowOrgCreationDialog(true)++ return (+ <>+ <AwsMarketplaceInterstitial>+ <div className="flex flex-col gap-5">+ {showAutoRenewalWarning && (+ <AwsMarketplaceAutoRenewalWarning+ awsContractEndDate={onboardingInfo.aws_contract_end_date}+ awsContractSettingsUrl={onboardingInfo.aws_contract_settings_url}+ />+ )}++ <InterstitialAccountRow displayName={displayName} />++ {hasAnyOrganizations && (+ <OrganizationSelector+ organizations={linkableOrganizations}+ unavailableOrganizations={unavailableOrganizations}+ unavailableReason="These may have outstanding invoices or existing marketplace links."+ getUnavailableOrganizationDescription={(organization) =>+ getOrganizationUnavailableReason(+ eligibilityByOrganizationSlug.get(organization.slug)?.reasons[0]+ )+ }+ selectedSlug={selectedOrgSlug}+ disabled={isLinking}+ onSelect={setSelectedOrgSlug}+ createLabel={hasLinkableOrganizations ? 'Create new organization' : undefined}+ onCreate={hasLinkableOrganizations ? () => setShowOrgCreationDialog(true) : undefined}+ />+ )}++ {!hasLinkableOrganizations && hasAnyOrganizations && (+ <Admonition+ type="warning"+ description="None of your current organizations can be linked to this AWS Marketplace subscription."+ />+ )}++ <div className="flex flex-col gap-5">+ <Button+ type="primary"+ block+ loading={isLinking}+ disabled={hasLinkableOrganizations && (!selectedOrgSlug || isLinking)}+ onClick={primaryAction}+ >+ {primaryLabel}+ </Button>+ <p className="text-center text-xs text-foreground-lighter text-balance">+ <InlineLink href={`${DOCS_URL}/guides/platform/aws-marketplace`}>+ Learn more+ </InlineLink>{' '}+ about billing through AWS.+ </p>+ </div>+ </div>+ </AwsMarketplaceInterstitial>++ {buyerId && (+ <NewAwsMarketplaceOrgModal+ visible={showOrgCreationDialog}+ onClose={() => setShowOrgCreationDialog(false)}+ buyerId={buyerId}+ onSuccess={(newlyCreatedOrgSlug) => {+ setShowOrgCreationDialog(false)+ setLinkedOrgSlug(newlyCreatedOrgSlug)+ }}+ />+ )}+ </>+ )+}diff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingPlaceholder.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingPlaceholder.tsxdeleted file mode 100644index 1a613bfe9f6..00000000000--- a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingPlaceholder.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { Skeleton } from '@ui/components/shadcn/ui/skeleton'--import {- ScaffoldSection,- ScaffoldSectionContent,- ScaffoldSectionDetail,-} from '@/components/layouts/Scaffold'--const AwsMarketplaceOnboardingPlaceholder = () => {- return (- <ScaffoldSection>- <ScaffoldSectionDetail>- {Array(1)- .fill(0)- .map((_, i) => (- <Skeleton key={i} className="w-full h-[110px] rounded-md" />- ))}- </ScaffoldSectionDetail>- <ScaffoldSectionContent className="lg:ml-10">- {Array(3)- .fill(0)- .map((_, i) => (- <Skeleton key={i} className="w-full h-[110px] rounded-md" />- ))}- </ScaffoldSectionContent>- </ScaffoldSection>- )-}--export default AwsMarketplaceOnboardingPlaceholderdiff --git a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingSuccessModal.tsx b/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingSuccessModal.tsxdeleted file mode 100644index 1402382228b..00000000000--- a/apps/studio/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingSuccessModal.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { Dialog, DialogContent, DialogFooter, DialogSection } from '@ui/components/shadcn/ui/dialog'-import { Button } from 'ui'--interface Props {- visible: boolean- onClose: () => void-}--const AwsMarketplaceOnboardingSuccessModal = ({ visible, onClose }: Props) => {- return (- <Dialog- open={visible}- onOpenChange={(open) => {- if (!open) onClose()- }}- >- <DialogContent- onOpenAutoFocus={(event) => event.preventDefault()}- size="xlarge"- hideClose={true}- onEscapeKeyDown={(e) => e.preventDefault()}- onPointerDownOutside={(e) => e.preventDefault()}- >- <DialogSection>- <div className="p-4 flex flex-col">- <h1 className="text-xl mb-4">AWS Marketplace Setup completed</h1>- <p className="text-foreground-light text-sm">- The organization is now managed and billed through AWS Marketplace.- </p>- </div>- </DialogSection>- <DialogFooter>- <Button size="medium" onClick={onClose}>- Go to Organization- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}--export default AwsMarketplaceOnboardingSuccessModaldiff --git a/apps/studio/components/interfaces/Organization/OrganizationCard.tsx b/apps/studio/components/interfaces/Organization/OrganizationCard.tsxindex b33ecb67d0e..ae5a4afb41e 100644--- a/apps/studio/components/interfaces/Organization/OrganizationCard.tsx+++ b/apps/studio/components/interfaces/Organization/OrganizationCard.tsx@@ -89,23 +89,46 @@ export const OrganizationCard = ({export const CreateOrganizationCard = ({params = {},label = 'Create new organization',+ onClick,+ disabled,}: {params?: { [key: string]: string }label?: string+ onClick?: () => void+ disabled?: boolean}) => {const createOrganizationHref = `/new${Object.keys(params).length > 0 ? `?${new URLSearchParams(params).toString()}` : ''}`+ const card = (+ <ActionCard+ bgColor="bg border"+ className={cn(+ 'flex items-center min-h-[70px] [&>div]:w-full [&>div]:items-center max-h-min',+ 'border-dashed shadow-none transition-colors group-hover:border-default group-hover:bg-surface-200'+ )}+ icon={<Plus size={18} strokeWidth={1} className="text-foreground" />}+ title={label}+ />+ )- return (- <Link href={createOrganizationHref}>- <ActionCard- bgColor="bg border"+ if (onClick) {+ return (+ <button+ type="button"+ disabled={disabled}+ onClick={onClick}className={cn(- 'flex items-center min-h-[70px] [&>div]:w-full [&>div]:items-center max-h-min',- 'border-dashed shadow-none transition-colors group-hover:border-default group-hover:bg-surface-200'+ 'group block w-full cursor-pointer text-left disabled:cursor-not-allowed disabled:opacity-50',+ disabled && 'pointer-events-none')}- icon={<Plus size={18} strokeWidth={1} className="text-foreground" />}- title={label}- />+ >+ {card}+ </button>+ )+ }++ return (+ <Link href={createOrganizationHref} className="group block">+ {card}</Link>)}diff --git a/apps/studio/components/layouts/LinkAwsMarketplaceLayout.tsx b/apps/studio/components/layouts/LinkAwsMarketplaceLayout.tsxdeleted file mode 100644index 7fc10d6357a..00000000000--- a/apps/studio/components/layouts/LinkAwsMarketplaceLayout.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { useTheme } from 'next-themes'-import Head from 'next/head'-import Image from 'next/legacy/image'-import type { PropsWithChildren } from 'react'-import { Separator } from 'ui'--import { withAuth } from '../../hooks/misc/withAuth'-import { useCustomContent } from '@/hooks/custom-content/useCustomContent'-import { BASE_PATH } from '@/lib/constants'--export interface LinkAwsMarketplaceLayoutProps {}--const LinkAwsMarketplaceLayout = ({- children,-}: PropsWithChildren<LinkAwsMarketplaceLayoutProps>) => {- const { resolvedTheme } = useTheme()- const { appTitle } = useCustomContent(['app:title'])-- return (- <>- <Head>- <title>AWS Marketplace Setup | {appTitle || 'Supabase'}</title>- </Head>- <main className="flex flex-col grow w-full h-full overflow-y-auto">- <div>- <div className="mx-auto px-4 sm:px-6">- <div className="max-w-xl flex justify-between items-center py-4">- <div className="flex justify-start lg:w-0 lg:flex-1">- <div>- <span className="sr-only">Supabase</span>- <Image- src={- resolvedTheme?.includes('dark')- ? `${BASE_PATH}/img/supabase-dark.svg`- : `${BASE_PATH}/img/supabase-light.svg`- }- alt="Supabase Logo"- height={20}- width={105}- />- </div>- </div>- </div>- </div>- </div>- <Separator />- <div className="flex flex-col justify-center grow mx-auto w-[90vw] space-y-4">- {children}- </div>- </main>- </>- )-}--export default withAuth(LinkAwsMarketplaceLayout)diff --git a/apps/studio/pages/aws-marketplace-onboarding.tsx b/apps/studio/pages/aws-marketplace-onboarding.tsxindex 64e00cb50be..f74ec3a7834 100644--- a/apps/studio/pages/aws-marketplace-onboarding.tsx+++ b/apps/studio/pages/aws-marketplace-onboarding.tsx@@ -1,76 +1,27 @@+import Head from 'next/head'import { useRouter } from 'next/router'-import AwsMarketplaceContractNotLinkable from '../components/interfaces/Organization/CloudMarketplace/AwsMarketplaceContractNotLinkable'-import AwsMarketplaceCreateNewOrg from '../components/interfaces/Organization/CloudMarketplace/AwsMarketplaceCreateNewOrg'-import { AwsMarketplaceLinkExistingOrg } from '../components/interfaces/Organization/CloudMarketplace/AwsMarketplaceLinkExistingOrg'-import AwsMarketplaceOnboardingPlaceholder from '../components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboardingPlaceholder'-import { useCloudMarketplaceContractLinkingEligibilityQuery } from '../components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query'-import LinkAwsMarketplaceLayout from '../components/layouts/LinkAwsMarketplaceLayout'-import {- ScaffoldContainer,- ScaffoldDivider,- ScaffoldHeader,- ScaffoldTitle,-} from '../components/layouts/Scaffold'-import { useOrganizationsQuery } from '../data/organizations/organizations-query'+import { AwsMarketplaceOnboardingScreen } from '@/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding'+import { withAuth } from '@/hooks/misc/withAuth'+import { buildStudioPageTitle } from '@/lib/page-title'import type { NextPageWithLayout } from '@/types'-const AwsMarketplaceOnboarding: NextPageWithLayout = () => {- const {- query: { buyer_id: buyerId },- } = useRouter()+const PAGE_TITLE = buildStudioPageTitle({ section: 'Link AWS Marketplace', brand: 'Supabase' })- const {- data: organizations,- isFetched: isOrganizationsFetched,- isSuccess: wasOrganizationsRequestSuccessful,- } = useOrganizationsQuery()+const AwsMarketplaceOnboardingPage: NextPageWithLayout = () => {+ const router = useRouter()+ const buyerId = typeof router.query.buyer_id === 'string' ? router.query.buyer_id : undefined- const {- data: contractLinkingEligibility,- isFetched: isContractLinkingEligibilityFetched,- isSuccess: wasEligibilityRequestSuccessful,- } = useCloudMarketplaceContractLinkingEligibilityQuery({- buyerId: buyerId as string,- })-- const renderContent = () => {- if (!isOrganizationsFetched || !isContractLinkingEligibilityFetched) {- return <AwsMarketplaceOnboardingPlaceholder />- }-- if (!wasOrganizationsRequestSuccessful || !wasEligibilityRequestSuccessful) {- return <p className="mt-4">Error loading AWS Marketplace setup page. Try again later.</p>- }-- if (!contractLinkingEligibility.eligibility.is_eligible) {- return (- <AwsMarketplaceContractNotLinkable- reason={contractLinkingEligibility.eligibility.reasons[0]}- />- )- }-- if (organizations?.length) {- return <AwsMarketplaceLinkExistingOrg organizations={organizations} />- }-- return <AwsMarketplaceCreateNewOrg />- }+ if (!router.isReady) return nullreturn (- <ScaffoldContainer>- <ScaffoldHeader>- <ScaffoldTitle>AWS Marketplace Setup</ScaffoldTitle>- </ScaffoldHeader>- <ScaffoldDivider />- {renderContent()}- </ScaffoldContainer>+ <>+ <Head>+ <title>{PAGE_TITLE}</title>+ </Head>+ <AwsMarketplaceOnboardingScreen buyerId={buyerId} />+ </>)}-AwsMarketplaceOnboarding.getLayout = (page) => (- <LinkAwsMarketplaceLayout>{page}</LinkAwsMarketplaceLayout>-)--export default AwsMarketplaceOnboarding+export default withAuth(AwsMarketplaceOnboardingPage)diff --git a/apps/studio/public/img/icons/aws-icon.svg b/apps/studio/public/img/icons/aws-icon.svgnew file mode 100644index 00000000000..3f95fa4fe6b--- /dev/null+++ b/apps/studio/public/img/icons/aws-icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="Layer_1" x="0" y="0" version="1.1" viewBox="0 0 304 182"><style>.st1{fill-rule:evenodd;clip-rule:evenodd;fill:#f90}</style><path d="M86.4 66.4c0 3.7.4 6.7 1.1 8.9.8 2.2 1.8 4.6 3.2 7.2.5.8.7 1.6.7 2.3 0 1-.6 2-1.9 3L83.2 92c-.9.6-1.8.9-2.6.9-1 0-2-.5-3-1.4-1.4-1.5-2.6-3.1-3.6-4.7-1-1.7-2-3.6-3.1-5.9Q59.2 94.7 41.5 94.7c-8.4 0-15.1-2.4-20-7.2s-7.4-11.2-7.4-19.2c0-8.5 3-15.4 9.1-20.6s14.2-7.8 24.5-7.8c3.4 0 6.9.3 10.6.8s7.5 1.3 11.5 2.2v-7.3c0-7.6-1.6-12.9-4.7-16-3.2-3.1-8.6-4.6-16.3-4.6-3.5 0-7.1.4-10.8 1.3s-7.3 2-10.8 3.4c-1.6.7-2.8 1.1-3.5 1.3s-1.2.3-1.6.3c-1.4 0-2.1-1-2.1-3.1v-4.9c0-1.6.2-2.8.7-3.5s1.4-1.4 2.8-2.1Q28.75 5 36.1 3.2C41 1.9 46.2 1.3 51.7 1.3c11.9 0 20.6 2.7 26.2 8.1 5.5 5.4 8.3 13.6 8.3 24.6v32.4zM45.8 81.6c3.3 0 6.7-.6 10.3-1.8s6.8-3.4 9.5-6.4c1.6-1.9 2.8-4 3.4-6.4s1-5.3 1-8.7v-4.2c-2.9-.7-6-1.3-9.2-1.7s-6.3-.6-9.4-.6c-6.7 0-11.6 1.3-14.9 4s-4.9 6.5-4.9 11.5c0 4.7 1.2 8.2 3.7 10.6 2.4 2.5 5.9 3.7 10.5 3.7m80.3 10.8c-1.8 0-3-.3-3.8-1-.8-.6-1.5-2-2.1-3.9L96.7 10.2c-.6-2-.9-3.3-.9-4 0-1.6.8-2.5 2.4-2.5h9.8c1.9 0 3.2.3 3.9 1 .8.6 1.4 2 2 3.9l16.8 66.2 15.6-66.2c.5-2 1.1-3.3 1.9-3.9s2.2-1 4-1h8c1.9 0 3.2.3 4 1 .8.6 1.5 2 1.9 3.9l15.8 67 17.3-67c.6-2 1.3-3.3 2-3.9.8-.6 2.1-1 3.9-1h9.3c1.6 0 2.5.8 2.5 2.5 0 .5-.1 1-.2 1.6s-.3 1.4-.7 2.5l-24.1 77.3q-.9 3-2.1 3.9c-.8.6-2.1 1-3.8 1h-8.6c-1.9 0-3.2-.3-4-1s-1.5-2-1.9-4L156 23l-15.4 64.4c-.5 2-1.1 3.3-1.9 4s-2.2 1-4 1zm128.5 2.7c-5.2 0-10.4-.6-15.4-1.8s-8.9-2.5-11.5-4c-1.6-.9-2.7-1.9-3.1-2.8s-.6-1.9-.6-2.8v-5.1c0-2.1.8-3.1 2.3-3.1q.9 0 1.8.3c.6.2 1.5.6 2.5 1 3.4 1.5 7.1 2.7 11 3.5 4 .8 7.9 1.2 11.9 1.2 6.3 0 11.2-1.1 14.6-3.3s5.2-5.4 5.2-9.5c0-2.8-.9-5.1-2.7-7s-5.2-3.6-10.1-5.2L246 52c-7.3-2.3-12.7-5.7-16-10.2-3.3-4.4-5-9.3-5-14.5q0-6.3 2.7-11.1c1.8-3.2 4.2-6 7.2-8.2 3-2.3 6.4-4 10.4-5.2s8.2-1.7 12.6-1.7c2.2 0 4.5.1 6.7.4 2.3.3 4.4.7 6.5 1.1 2 .5 3.9 1 5.7 1.6q2.7.9 4.2 1.8c1.4.8 2.4 1.6 3 2.5q.9 1.2.9 3.3v4.7c0 2.1-.8 3.2-2.3 3.2-.8 0-2.1-.4-3.8-1.2q-8.55-3.9-19.2-3.9c-5.7 0-10.2.9-13.3 2.8s-4.7 4.8-4.7 8.9c0 2.8 1 5.2 3 7.1s5.7 3.8 11 5.5l14.2 4.5c7.2 2.3 12.4 5.5 15.5 9.6s4.6 8.8 4.6 14c0 4.3-.9 8.2-2.6 11.6-1.8 3.4-4.2 6.4-7.3 8.8-3.1 2.5-6.8 4.3-11.1 5.6-4.5 1.4-9.2 2.1-14.3 2.1" style="fill:#fff"/><path d="M273.5 143.7c-32.9 24.3-80.7 37.2-121.8 37.2-57.6 0-109.5-21.3-148.7-56.7-3.1-2.8-.3-6.6 3.4-4.4 42.4 24.6 94.7 39.5 148.8 39.5 36.5 0 76.6-7.6 113.5-23.2 5.5-2.5 10.2 3.6 4.8 7.6" class="st1"/><path d="M287.2 128.1c-4.2-5.4-27.8-2.6-38.5-1.3-3.2.4-3.7-2.4-.8-4.5 18.8-13.2 49.7-9.4 53.3-5 3.6 4.5-1 35.4-18.6 50.2-2.7 2.3-5.3 1.1-4.1-1.9 4-9.9 12.9-32.2 8.7-37.5" class="st1"/></svg>diff --git a/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsx b/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsxnew file mode 100644index 00000000000..1ef732361d1--- /dev/null+++ b/apps/studio/tests/pages/aws-marketplace-onboarding.test.tsx@@ -0,0 +1,266 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { LOCAL_STORAGE_KEYS } from 'common'+import { http, HttpResponse } from 'msw'+import { beforeEach, describe, expect, test, vi } from 'vitest'++import { AwsMarketplaceOnboardingScreen } from '@/components/interfaces/Organization/CloudMarketplace/AwsMarketplaceOnboarding'+import type {+ CloudMarketplaceContractLinkingEligibility,+ CloudMarketplaceOnboardingInfo,+} from '@/components/interfaces/Organization/CloudMarketplace/cloud-marketplace-query'+import { API_URL } from '@/lib/constants'+import type { ProfileContextType } from '@/lib/profile'+import { createMockOrganization } from '@/tests/helpers'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock, mswServer } from '@/tests/lib/msw'+import type { Organization } from '@/types'++const DEFAULT_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 LINKABLE_ORG = createMockOrganization({+ id: 1,+ name: 'Acme Production',+ slug: 'acme-production',+ plan: { id: 'pro', name: 'Pro' },+})+const UNAVAILABLE_ORG = createMockOrganization({+ id: 2,+ name: 'Legacy Billing',+ slug: 'legacy-billing',+ plan: { id: 'team', name: 'Team' },+})++const ELIGIBLE_CONTRACT: CloudMarketplaceContractLinkingEligibility = {+ eligibility: {+ is_eligible: true,+ reasons: [],+ aws_agreement_id: 'agreement-test',+ },+}++function createOnboardingInfo({+ organizations = [LINKABLE_ORG, UNAVAILABLE_ORG],+ eligibleSlugs = [LINKABLE_ORG.slug],+}: {+ organizations?: Organization[]+ eligibleSlugs?: string[]+} = {}): CloudMarketplaceOnboardingInfo {+ return {+ aws_contract_auto_renewal: true,+ aws_contract_end_date: '2026-12-31T00:00:00.000Z',+ aws_contract_is_private_offer: false,+ aws_contract_settings_url: 'https://aws.amazon.com/marketplace',+ aws_contract_start_date: '2026-01-01T00:00:00.000Z',+ organization_linking_eligibility: organizations.map((organization) => ({+ slug: organization.slug,+ is_eligible: eligibleSlugs.includes(organization.slug),+ reasons: eligibleSlugs.includes(organization.slug) ? [] : ['ALREADY_MANAGED_BY_PARTNER_AWS'],+ })),+ plan_name_selected_on_marketplace: 'Team',+ }+}++function mockAwsEndpoints({+ organizations = [LINKABLE_ORG, UNAVAILABLE_ORG],+ eligibility = ELIGIBLE_CONTRACT,+ onboardingInfo = createOnboardingInfo({ organizations }),+}: {+ organizations?: Organization[]+ eligibility?: CloudMarketplaceContractLinkingEligibility+ onboardingInfo?: CloudMarketplaceOnboardingInfo+} = {}) {+ addAPIMock({+ method: 'get',+ path: '/platform/organizations',+ response: () => HttpResponse.json(organizations),+ })+ addAPIMock({+ method: 'get',+ path: '/platform/cloud-marketplace/buyers/:buyer_id/contract-linking-eligibility',+ response: () => HttpResponse.json(eligibility),+ })+ addAPIMock({+ method: 'get',+ path: '/platform/cloud-marketplace/buyers/:buyer_id/onboarding-info',+ response: () => HttpResponse.json(onboardingInfo),+ })+}++function renderScreen(props: Partial<Parameters<typeof AwsMarketplaceOnboardingScreen>[0]> = {}) {+ return customRender(<AwsMarketplaceOnboardingScreen buyerId="buyer-test" {...props} />, {+ profileContext: DEFAULT_PROFILE_CONTEXT,+ })+}++describe('AwsMarketplaceOnboardingScreen', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ window.localStorage.clear()+ })++ test('renders linkable and unavailable organizations and disables link without selection', async () => {+ const user = userEvent.setup()+ mockAwsEndpoints()+ renderScreen()++ await screen.findByText('Acme Production')+ const linkButton = screen.getByRole('button', { name: 'Link organization' })+ expect(linkButton).toBeDisabled()++ await user.click(screen.getByRole('button', { name: /Organizations that can't be linked/ }))+ expect(screen.getByText('Legacy Billing')).toBeInTheDocument()+ expect(screen.getByText('Already linked to AWS Marketplace')).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: /Acme Production/ }))+ expect(linkButton).toBeEnabled()+ })++ test('calls link mutation with buyerId and slug', async () => {+ const user = userEvent.setup()+ let linkRequest: { slug?: string; body?: unknown } | undefined++ mockAwsEndpoints()+ mswServer.use(+ http.put(+ `${API_URL}/platform/organizations/:slug/cloud-marketplace/link`,+ async ({ params, request }) => {+ linkRequest = {+ slug: String(params.slug),+ body: await request.json(),+ }+ return HttpResponse.json({})+ }+ )+ )++ renderScreen()++ await user.click(await screen.findByRole('button', { name: /Acme Production/ }))+ await user.click(screen.getByRole('button', { name: 'Link organization' }))++ await waitFor(() => {+ expect(linkRequest).toEqual({+ slug: 'acme-production',+ body: { buyer_id: 'buyer-test' },+ })+ })+ await screen.findByText('Organization linked')+ })++ test('renders setup unavailable when the buyer ID is missing', async () => {+ renderScreen({ buyerId: undefined })++ expect(await screen.findByText('Setup unavailable')).toBeInTheDocument()+ expect(screen.getByText('buyer_id')).toBeInTheDocument()+ })++ test('renders an error state when onboarding info fails to load', async () => {+ mockAwsEndpoints()+ mswServer.use(+ http.get(`${API_URL}/platform/cloud-marketplace/buyers/:buyer_id/onboarding-info`, () =>+ HttpResponse.json({ message: 'Failed to load onboarding info' }, { status: 500 })+ )+ )++ renderScreen()++ expect(await screen.findByText('Unable to load setup')).toBeInTheDocument()+ })++ test('renders the generic ineligible state', async () => {+ mockAwsEndpoints({+ eligibility: {+ eligibility: {+ is_eligible: false,+ reasons: [],+ aws_agreement_id: 'agreement-test',+ },+ },+ })++ renderScreen()++ expect(+ await screen.findByText('This AWS Marketplace subscription cannot be linked right now')+ ).toBeInTheDocument()+ expect(screen.getByText('If the problem persists, contact support.')).toBeInTheDocument()+ })++ test('renders the already-linked ineligible state', async () => {+ mockAwsEndpoints({+ eligibility: {+ eligibility: {+ is_eligible: false,+ reasons: ['AGREEMENT_BASED_OFFER'],+ aws_agreement_id: 'agreement-test',+ },+ },+ })++ renderScreen()++ expect(await screen.findByText('No action required')).toBeInTheDocument()+ })++ test('promotes the last visited organization into the first visible organizations', async () => {+ const organizations = [+ createMockOrganization({ id: 1, name: 'Alpha Team', slug: 'alpha-team' }),+ createMockOrganization({ id: 2, name: 'Beta Team', slug: 'beta-team' }),+ createMockOrganization({ id: 3, name: 'Delta Team', slug: 'delta-team' }),+ createMockOrganization({ id: 4, name: 'Gamma Team', slug: 'gamma-team' }),+ createMockOrganization({ id: 5, name: 'Zeta Team', slug: 'zeta-team' }),+ ]++ window.localStorage.setItem(+ LOCAL_STORAGE_KEYS.LAST_VISITED_ORGANIZATION,+ JSON.stringify('zeta-team')+ )+ mockAwsEndpoints({+ organizations,+ onboardingInfo: createOnboardingInfo({+ organizations,+ eligibleSlugs: organizations.map(({ slug }) => slug),+ }),+ })+ renderScreen()++ const zeta = await screen.findByText('Zeta Team')+ const alpha = await screen.findByText('Alpha Team')+ expect(zeta.compareDocumentPosition(alpha) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Show 2 more' })).toBeInTheDocument()+ })++ test('renders a create organization action when there are no existing organizations', async () => {+ mockAwsEndpoints({+ organizations: [],+ onboardingInfo: createOnboardingInfo({ organizations: [] }),+ })++ renderScreen()++ expect(await screen.findByRole('button', { name: 'Create organization' })).toBeInTheDocument()+ expect(+ screen.queryByRole('button', { name: /Create new organization/ })+ ).not.toBeInTheDocument()+ })+})