The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Joshen/fe 2900 migrate stripe sync engine to new UI (#44427)
Joshen Lim2a018833fd56
diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.tsxindex 74549e79a40..210c520fe44 100644--- a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.tsx+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTab.tsx@@ -16,6 +16,7 @@ export interface IntegrationOverviewTabProps {hideRequiredExtensionsSection?: boolean}+/** [Joshen] This will eventually get replaced by IntegrationOverviewTabV2 */export const IntegrationOverviewTab = ({actions,alert,diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsxindex 9406d17efb2..ec29b871a75 100644--- a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.test.tsx@@ -1,4 +1,4 @@-import { screen, waitFor } from '@testing-library/dom'+import { fireEvent, screen, waitFor } from '@testing-library/dom'import userEvent from '@testing-library/user-event'import { mockAnimationsApi } from 'jsdom-testing-mocks'import { customRender } from 'tests/lib/custom-render'@@ -6,7 +6,7 @@ import { routerMock } from 'tests/lib/route-mock'import { beforeEach, describe, expect, it, vi } from 'vitest'import { IntegrationDefinition } from '../../Landing/Integrations.constants'-import { InstallIntegrationSheet } from './InstallIntegrationSheet'+import { InstallIntegrationSheet } from './InstallIntegrationSheet/InstallIntegrationSheet'mockAnimationsApi()@@ -113,10 +113,15 @@ describe('InstallIntegrationSheet', () => {)await userEvent.click(screen.getByRole('button', { name: 'Install integration' }))- await userEvent.click(getInstallButton())++ // SheetContent renders via a Radix portal, placing the submit button outside+ // the <form> in the DOM. jsdom doesn't support the HTML `form` attribute on+ // buttons, so we submit the form directly instead of clicking the button.+ const form = document.getElementById('installation-settings')!+ fireEvent.submit(form)await waitFor(() => {- expect(mockCommand).toHaveBeenCalledWith({ ref: 'default' })+ expect(mockCommand).toHaveBeenCalledWith(expect.objectContaining({ ref: 'default' }))})expect(mockExecuteSql).not.toHaveBeenCalled()})diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.tsxdeleted file mode 100644index c3680db6fc8..00000000000--- a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet.tsx+++ /dev/null@@ -1,433 +0,0 @@-import { useEffect, useState } from 'react'-import { toast } from 'sonner'-import {- Accordion_Shadcn_,- AccordionContent_Shadcn_,- AccordionItem_Shadcn_,- AccordionTrigger_Shadcn_,- Badge,- Button,- Card,- CardContent,- cn,- DialogSectionSeparator,- Select_Shadcn_,- SelectContent_Shadcn_,- SelectItem_Shadcn_,- SelectSeparator_Shadcn_,- SelectTrigger_Shadcn_,- SelectValue_Shadcn_,- Sheet,- SheetClose,- SheetContent,- SheetDescription,- SheetFooter,- SheetHeader,- SheetSection,- SheetTitle,- SheetTrigger,- Tabs_Shadcn_,- TabsContent_Shadcn_,- TabsList_Shadcn_,- TabsTrigger_Shadcn_,-} from 'ui'-import { CodeBlock } from 'ui-patterns/CodeBlock'-import { Input } from 'ui-patterns/DataInputs/Input'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'--import { IntegrationDefinition } from '../../Landing/Integrations.constants'-import { getEnableExtensionsSQL, getExtensionDefaultSchema } from './IntegrationOverviewTabV2.utils'-import { extensionsWithRecommendedSchemas } from '@/components/interfaces/Database/Extensions/Extensions.constants'-import { useDatabaseExtensionEnableMutation } from '@/data/database-extensions/database-extension-enable-mutation'-import { useDatabaseExtensionsQuery } from '@/data/database-extensions/database-extensions-query'-import { useSchemasQuery } from '@/data/database/schemas-query'-import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'-import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'-import { useProtectedSchemas } from '@/hooks/useProtectedSchemas'-import { ResponseError } from '@/types'--interface InstallIntegrationSheetProps {- integration: IntegrationDefinition-}--/**- * [Joshen] Trying to figure out what the ideal data structure is between local + remote integrations- * So it might be a bit messy for now as we get more context and build out this UI- *- * If the integration provides its own SQL installation command, we'll use that- * Otherwise if the integration provides its own SQL installation query, we'll use that through the query endpoint- * Else if the integration only requires extensions, dashboard will generate the queries and fire through the query endpoint- */--export const InstallIntegrationSheet = ({ integration }: InstallIntegrationSheetProps) => {- const { data: project } = useSelectedProjectQuery()- const { data: protectedSchemas } = useProtectedSchemas({ excludeSchemas: ['extensions'] })-- const [open, setOpen] = useState(false)- const [isInstalling, setIsInstalling] = useState(false)-- const {- icon,- name,- installationSql,- installationCommand,- missingExtensionsAlert,- requiredExtensions: requiredExtensionNames,- } = integration-- const allowExtensionCustomSchema = !installationSql- const involvesExtensions = requiredExtensionNames.length > 0- // [Joshen] Will hook these up in the future, applicable for stripe sync engine- const involvesEdgeFunctions = false-- const { data: extensions = [], isSuccess: isSuccessExtensions } = useDatabaseExtensionsQuery(- { projectRef: project?.ref, connectionString: project?.connectionString },- { enabled: involvesExtensions }- )-- const { data: schemas = [] } = useSchemasQuery(- { projectRef: project?.ref, connectionString: project?.connectionString },- { enabled: involvesExtensions }- )-- const defaultExtensionsSchema = Object.fromEntries(- requiredExtensionNames.map((extName) => {- const ext = extensions.find((x) => x.name === extName)- const defaultSchema = getExtensionDefaultSchema(ext)- return [extName, { schema: defaultSchema ?? 'extensions', value: undefined }]- })- )- const [extensionsSchema, setExtensionsSchema] = useState<{- [key: string]: { schema: string; value: string | undefined }- }>(defaultExtensionsSchema)-- const requiredExtensions = extensions.filter((ext) => requiredExtensionNames.includes(ext.name))- // [Joshen] Integration requires extensions that are not available to install on the current database image- const hasMissingExtensions = requiredExtensionNames.length !== requiredExtensions.length-- const availableSchemas = schemas.filter(- (schema) => !protectedSchemas.some((protectedSchema) => protectedSchema.name === schema.name)- )-- const { mutateAsync: executeSql } = useExecuteSqlMutation({ onError: () => {} })- const { mutateAsync: enableExtension } = useDatabaseExtensionEnableMutation({ onError: () => {} })-- const enableExtensionsSQL = getEnableExtensionsSQL({- extensions: requiredExtensions.filter((ext) => !ext.installed_version),- extensionsSchema,- })- const installationSQLContent = installationSql ?? enableExtensionsSQL-- const onInstallIntegration = async () => {- if (!project) return console.error('Project is required')-- setIsInstalling(true)- const toastId = toast.loading(`Installing ${name}`)-- try {- if (installationCommand) {- await installationCommand({ ref: project.ref })- } else if (installationSql) {- await installIntegrationViaSQL()- } else {- await installIntegrationExtensions()- }-- toast.success(`Successfully installed ${name}`, { id: toastId })- setOpen(false)- } catch (error) {- toast.error(`Failed to install ${name}: ${(error as ResponseError).message}`, {- id: toastId,- })- } finally {- setIsInstalling(false)- }- }-- const installIntegrationViaSQL = async () => {- if (!project) return console.error('Project is required')- if (!installationSql) return console.error('Installation SQL is required')-- const { ref: projectRef, connectionString } = project- await executeSql({ projectRef, connectionString, sql: installationSql })- }-- const installIntegrationExtensions = async () => {- if (!project) return console.error('Project is required')-- const { ref: projectRef, connectionString } = project- const results = await Promise.allSettled(- requiredExtensions- .filter((ext) => !ext.installed_version)- .map((ext) => {- const { name, default_version: version } = ext- const createSchema = extensionsSchema[name].schema === 'custom'-- const defaultSchema = getExtensionDefaultSchema(ext)- const schema =- defaultSchema ||- (createSchema- ? (extensionsSchema[name].value as string)- : extensionsSchema[name].schema)-- return enableExtension({- projectRef,- connectionString,- schema,- name,- version,- cascade: true,- createSchema,- })- })- )-- const failure = results.find((r) => r.status === 'rejected')- if (failure) throw new Error(failure.reason.message)- }-- useEffect(() => {- if (isSuccessExtensions) return- setExtensionsSchema(defaultExtensionsSchema)- }, [isSuccessExtensions, defaultExtensionsSchema])-- return (- <Sheet open={open} onOpenChange={setOpen}>- <SheetTrigger asChild>- <Button type="primary">Install integration</Button>- </SheetTrigger>- <SheetContent- size="default"- aria-describedby={undefined}- className="flex flex-col gap-0 !w-[550px]"- >- <SheetHeader className="flex items-center gap-x-4">- <div className="shrink-0 w-11 h-11 relative bg-white border rounded-md flex items-center justify-center">- {icon()}- </div>- <div className="flex flex-col">- <SheetTitle>Install {name}</SheetTitle>- <SheetDescription>Review and configure this integration</SheetDescription>- </div>- </SheetHeader>-- <div className="flex-grow">- <SheetSection className="flex flex-col gap-y-4 py-5">- <div>- <h4>Installs</h4>- <p className="text-sm text-foreground-light">- What this integration will run on your project- </p>- </div>-- {hasMissingExtensions && missingExtensionsAlert}-- <Card>- <CardContent className="px-0 pt-1.5 pb-0">- <Tabs_Shadcn_ defaultValue="extensions">- <TabsList_Shadcn_ className="px-4 space-x-4">- {involvesExtensions && (- <>- <TabsTrigger_Shadcn_- value="extensions"- className="font-mono uppercase text-xs"- >- Extensions- </TabsTrigger_Shadcn_>- <TabsTrigger_Shadcn_ value="sql" className="font-mono uppercase text-xs">- SQL- </TabsTrigger_Shadcn_>- </>- )}- {involvesEdgeFunctions && (- <TabsTrigger_Shadcn_- value="edge_functions"- className="font-mono uppercase text-xs"- >- Edge Functions- </TabsTrigger_Shadcn_>- )}- </TabsList_Shadcn_>-- <TabsContent_Shadcn_ value="extensions" className="mt-0 divide-y">- {requiredExtensionNames.map((extName) => {- const ext = extensions.find((x) => x.name === extName)- return (- <div key={extName} className="py-3 px-4 flex items-center justify-between">- <code className="text-xs">{extName}</code>- {!ext ? (- <Badge>Unavailable</Badge>- ) : ext.installed_version ? (- <Badge>Installed</Badge>- ) : (- <Badge>Required</Badge>- )}- </div>- )- })}- </TabsContent_Shadcn_>- <TabsContent_Shadcn_ value="sql" className="mt-0">- <CodeBlock- hideCopy- hideLineNumbers- language="pgsql"- value={installationSQLContent}- wrapperClassName={cn('[&_pre]:px-4 [&_pre]:py-3')}- className="border-0 rounded-none [&_code]:text-[12px] [&_code]:text-foreground max-h-80"- />- </TabsContent_Shadcn_>- <TabsContent_Shadcn_ value="edge_functions" className="mt-0">- TBD- </TabsContent_Shadcn_>- </Tabs_Shadcn_>- </CardContent>- </Card>- </SheetSection>-- {allowExtensionCustomSchema && (- <>- <DialogSectionSeparator />-- <SheetSection>- <Accordion_Shadcn_ type="single" collapsible>- <AccordionItem_Shadcn_ value="advanced-settings" className="border-none">- <AccordionTrigger_Shadcn_ className="font-normal gap-2 py-0 justify-between text-sm hover:no-underline">- Advanced settings- </AccordionTrigger_Shadcn_>- <AccordionContent_Shadcn_ className="!pb-0 pt-3 [&>div]:flex [&>div]:flex-col [&>div]:gap-y-4">- <p className="text-foreground-light">- Select which schemas to install the database extensions under- </p>- {requiredExtensionNames.map((extName) => {- const ext = extensions.find((x) => x.name === extName)- const extMeta = extensionsSchema[extName]- const { schema, value } = extMeta- const recommendedSchema = extensionsWithRecommendedSchemas[extName]- const defaultSchema = getExtensionDefaultSchema(ext)-- return (- <FormItemLayout- key={extName}- isReactForm={false}- layout="horizontal"- label={extName}- description={- ext?.installed_version ? (- <>- Installed in{' '}- <code className="text-code-inline">{ext.schema}</code> schema- </>- ) : defaultSchema ? (- <>- Must be installed in the{' '}- <code className="text-code-inline">{defaultSchema}</code> schema- </>- ) : recommendedSchema ? (- <>- Use the{' '}- <code className="text-code-inline">{recommendedSchema}</code>{' '}- schema for full compatibility with related features- </>- ) : undefined- }- >- <Select_Shadcn_- disabled={!!defaultSchema || !!ext?.installed_version}- value={schema}- onValueChange={(schema) =>- setExtensionsSchema((prev) => ({- ...prev,- [extName]: {- schema,- value: schema === 'custom' ? extName : undefined,- },- }))- }- >- <SelectTrigger_Shadcn_>- <SelectValue_Shadcn_ placeholder="Select a schema" />- </SelectTrigger_Shadcn_>- <SelectContent_Shadcn_>- <SelectItem_Shadcn_ value="custom">- Create a new schema- </SelectItem_Shadcn_>- <SelectSeparator_Shadcn_ />- {availableSchemas.map((schema) => {- return (- <SelectItem_Shadcn_ key={schema.id} value={schema.name}>- {schema.name}- {schema.name === recommendedSchema ? (- <Badge className="ml-2" variant="success">- Recommended- </Badge>- ) : schema.name === 'extensions' ? (- <Badge className="ml-2">Default</Badge>- ) : null}- </SelectItem_Shadcn_>- )- })}- {defaultSchema &&- !availableSchemas.some(- (schema) => schema.name === defaultSchema- ) ? (- <SelectItem_Shadcn_ key={defaultSchema} value={defaultSchema}>- {defaultSchema}- <Badge className="ml-2">Default</Badge>- </SelectItem_Shadcn_>- ) : null}- </SelectContent_Shadcn_>- </Select_Shadcn_>-- {schema === 'custom' && (- <FormItemLayout- isReactForm={false}- className="mt-2"- label="Provide a name for your new schema"- >- <Input- value={value}- onChange={(e) =>- setExtensionsSchema((prev) => ({- ...prev,- [extName]: {- schema: prev[extName].schema,- value: e.target.value,- },- }))- }- placeholder="Provide a name for your schema"- />- </FormItemLayout>- )}- </FormItemLayout>- )- })}- </AccordionContent_Shadcn_>- </AccordionItem_Shadcn_>- </Accordion_Shadcn_>- </SheetSection>- </>- )}-- <DialogSectionSeparator />- </div>-- <SheetFooter>- <SheetClose asChild>- <Button type="default" disabled={isInstalling}>- Cancel- </Button>- </SheetClose>- <Button- type="primary"- disabled={hasMissingExtensions}- loading={isInstalling}- onClick={onInstallIntegration}- >- Install integration- </Button>- </SheetFooter>- </SheetContent>- </Sheet>- )-}diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/AdvancedSettings.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/AdvancedSettings.tsxnew file mode 100644index 00000000000..75a227d7be0--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/AdvancedSettings.tsx@@ -0,0 +1,169 @@+import { extensionsWithRecommendedSchemas } from 'components/interfaces/Database/Extensions/Extensions.constants'+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'+import { useSchemasQuery } from 'data/database/schemas-query'+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'+import { useProtectedSchemas } from 'hooks/useProtectedSchemas'+import { type Dispatch, type SetStateAction } from 'react'+import {+ Accordion_Shadcn_,+ AccordionContent_Shadcn_,+ AccordionItem_Shadcn_,+ AccordionTrigger_Shadcn_,+ Badge,+ Select_Shadcn_,+ SelectContent_Shadcn_,+ SelectItem_Shadcn_,+ SelectSeparator_Shadcn_,+ SelectTrigger_Shadcn_,+ SelectValue_Shadcn_,+ SheetSection,+} from 'ui'+import { Input } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import { getExtensionDefaultSchema } from '../IntegrationOverviewTabV2.utils'+import { type ExtensionsSchema, type InstallIntegrationSheetProps } from './InstallIntegrationSheet'++type AdvancedSettingsProps = InstallIntegrationSheetProps & {+ extensionsSchema: ExtensionsSchema+ setExtensionsSchema: Dispatch<SetStateAction<ExtensionsSchema>>+}++export const AdvancedSettings = ({+ integration,+ extensionsSchema,+ setExtensionsSchema,+}: AdvancedSettingsProps) => {+ const { data: project } = useSelectedProjectQuery()+ const { data: protectedSchemas } = useProtectedSchemas({ excludeSchemas: ['extensions'] })+ const { requiredExtensions: requiredExtensionNames } = integration++ const involvesExtensions = requiredExtensionNames.length > 0+ const { data: extensions = [] } = useDatabaseExtensionsQuery(+ { projectRef: project?.ref, connectionString: project?.connectionString },+ { enabled: involvesExtensions }+ )++ const { data: schemas = [] } = useSchemasQuery(+ { projectRef: project?.ref, connectionString: project?.connectionString },+ { enabled: involvesExtensions }+ )+ const availableSchemas = schemas.filter(+ (schema) => !protectedSchemas.some((protectedSchema) => protectedSchema.name === schema.name)+ )++ return (+ <SheetSection>+ <Accordion_Shadcn_ type="single" collapsible>+ <AccordionItem_Shadcn_ value="advanced-settings" className="border-none">+ <AccordionTrigger_Shadcn_ className="font-normal gap-2 py-0 justify-between text-sm hover:no-underline">+ Advanced settings+ </AccordionTrigger_Shadcn_>+ <AccordionContent_Shadcn_ className="!pb-0 pt-3 [&>div]:flex [&>div]:flex-col [&>div]:gap-y-4">+ <p className="text-foreground-light">+ Select which schemas to install the database extensions under+ </p>+ {requiredExtensionNames.map((extName) => {+ const ext = extensions.find((x) => x.name === extName)+ const extMeta = extensionsSchema[extName]+ const { schema, value } = extMeta+ const recommendedSchema = extensionsWithRecommendedSchemas[extName]+ const defaultSchema = getExtensionDefaultSchema(ext)++ return (+ <FormItemLayout+ key={extName}+ isReactForm={false}+ layout="horizontal"+ label={extName}+ description={+ ext?.installed_version ? (+ <>+ Installed in <code className="text-code-inline">{ext.schema}</code> schema+ </>+ ) : defaultSchema ? (+ <>+ Must be installed in the{' '}+ <code className="text-code-inline">{defaultSchema}</code> schema+ </>+ ) : recommendedSchema ? (+ <>+ Use the <code className="text-code-inline">{recommendedSchema}</code> schema+ for full compatibility with related features+ </>+ ) : undefined+ }+ >+ <Select_Shadcn_+ disabled={!!defaultSchema || !!ext?.installed_version}+ value={schema}+ onValueChange={(schema) =>+ setExtensionsSchema((prev) => ({+ ...prev,+ [extName]: {+ schema,+ value: schema === 'custom' ? extName : undefined,+ },+ }))+ }+ >+ <SelectTrigger_Shadcn_>+ <SelectValue_Shadcn_ placeholder="Select a schema" />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectItem_Shadcn_ value="custom">Create a new schema</SelectItem_Shadcn_>+ <SelectSeparator_Shadcn_ />+ {availableSchemas.map((schema) => {+ return (+ <SelectItem_Shadcn_ key={schema.id} value={schema.name}>+ {schema.name}+ {schema.name === recommendedSchema ? (+ <Badge className="ml-2" variant="success">+ Recommended+ </Badge>+ ) : schema.name === 'extensions' ? (+ <Badge className="ml-2">Default</Badge>+ ) : null}+ </SelectItem_Shadcn_>+ )+ })}+ {defaultSchema &&+ !availableSchemas.some((schema) => schema.name === defaultSchema) ? (+ <SelectItem_Shadcn_ key={defaultSchema} value={defaultSchema}>+ {defaultSchema}+ <Badge className="ml-2">Default</Badge>+ </SelectItem_Shadcn_>+ ) : null}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>++ {schema === 'custom' && (+ <FormItemLayout+ isReactForm={false}+ className="mt-2"+ label="Provide a name for your new schema"+ >+ <Input+ value={value}+ onChange={(e) =>+ setExtensionsSchema((prev) => ({+ ...prev,+ [extName]: {+ schema: prev[extName].schema,+ value: e.target.value,+ },+ }))+ }+ placeholder="Provide a name for your schema"+ />+ </FormItemLayout>+ )}+ </FormItemLayout>+ )+ })}+ </AccordionContent_Shadcn_>+ </AccordionItem_Shadcn_>+ </Accordion_Shadcn_>+ </SheetSection>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallIntegrationSheet.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallIntegrationSheet.tsxnew file mode 100644index 00000000000..387a34e7417--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallIntegrationSheet.tsx@@ -0,0 +1,283 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { type IntegrationDefinition } from 'components/interfaces/Integrations/Landing/Integrations.constants'+import { useTrack } from 'lib/telemetry/track'+import { useEffect, useMemo, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import { toast } from 'sonner'+import {+ Button,+ DialogSectionSeparator,+ Form_Shadcn_,+ Sheet,+ SheetClose,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ SheetTrigger,+} from 'ui'+import * as z from 'zod'++import { getExtensionDefaultSchema } from '../IntegrationOverviewTabV2.utils'+import { AdvancedSettings } from './AdvancedSettings'+import { InstallationOverview } from './InstallationOverview'+import { InstallationSettings } from './InstallationSettings'+import { useDatabaseExtensionEnableMutation } from '@/data/database-extensions/database-extension-enable-mutation'+import {+ DatabaseExtension,+ useDatabaseExtensionsQuery,+} from '@/data/database-extensions/database-extensions-query'+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { ResponseError } from '@/types'++export interface InstallIntegrationSheetProps {+ integration: IntegrationDefinition+}++export type ExtensionsSchema = { [key: string]: { schema: string; value: string | undefined } }++const formId = 'installation-settings'++/**+ * [Joshen] Trying to figure out what the ideal data structure is between local + remote integrations+ * So it might be a bit messy for now as we get more context and build out this UI+ *+ * If the integration provides its own SQL installation command, we'll use that+ * Otherwise if the integration provides its own SQL installation query, we'll use that through the query endpoint+ * Else if the integration only requires extensions, dashboard will generate the queries and fire through the query endpoint+ *+ */++export const InstallIntegrationSheet = ({ integration }: InstallIntegrationSheetProps) => {+ const track = useTrack()+ const { data: project } = useSelectedProjectQuery()++ const [open, setOpen] = useState(false)+ const [isInstalling, setIsInstalling] = useState(false)++ const {+ icon,+ name,+ inputs = {},+ installationSql,+ installationCommand,+ checkInstallationStatus,+ requiredExtensions: requiredExtensionNames,+ } = integration++ const allowExtensionCustomSchema = !installationSql+ const involvesExtensions = requiredExtensionNames.length > 0++ const schema = useMemo(() => {+ let baseSchema = z.object({})+ Object.entries(inputs).forEach((entry) => {+ const [key, input] = entry+ baseSchema = baseSchema.extend({+ [key]: z.string().min(1, `Please provide a value for ${input.label}`),+ })+ })+ return baseSchema+ }, [inputs])++ const defaultValues = useMemo(() => {+ let values = {} as Record<string, string>+ Object.entries(inputs).forEach((entry) => {+ const [key] = entry+ values[key] = ''+ })+ return values+ }, [inputs])++ const form = useForm<Record<string, string>>({+ mode: 'onBlur',+ reValidateMode: 'onBlur',+ resolver: zodResolver(schema),+ defaultValues,+ })++ const { data: extensions = [], isSuccess: isSuccessExtensions } = useDatabaseExtensionsQuery(+ { projectRef: project?.ref, connectionString: project?.connectionString },+ { enabled: involvesExtensions }+ )++ const defaultExtensionsSchema = useMemo(+ () =>+ Object.fromEntries(+ requiredExtensionNames.map((extName) => {+ const ext = extensions.find((x) => x.name === extName)+ const defaultSchema = getExtensionDefaultSchema(ext)+ return [extName, { schema: defaultSchema ?? 'extensions', value: undefined }]+ })+ ),+ [requiredExtensionNames, extensions]+ )+ const [extensionsSchema, setExtensionsSchema] =+ useState<ExtensionsSchema>(defaultExtensionsSchema)++ const requiredExtensions = extensions.filter((ext) => requiredExtensionNames.includes(ext.name))+ const requiredExtensionsToBeInstalled = requiredExtensions.filter((ext) => !ext.installed_version)+ // [Joshen] Integration requires extensions that are not available to install on the current database image+ const hasMissingExtensions = requiredExtensionNames.length !== requiredExtensions.length++ const { mutateAsync: enableExtension } = useDatabaseExtensionEnableMutation({ onError: () => {} })++ /**+ * [Joshen] This is a bit messy again while we're figuring out requirements+ * If the integration has required extensions that are yet to be installed, we'll install those+ * AND if the integration has a provided installation command, we'll run that too+ */+ const onSubmit: SubmitHandler<Record<string, string>> = async (values) => {+ if (!project) return console.error('Project is required')++ setIsInstalling(true)+ const toastId = toast.loading(`Installing ${name}`)++ try {+ if (requiredExtensionsToBeInstalled.length > 0) {+ toast.loading(`Installing required database extensions`, { id: toastId })+ await installRequiredIntegrationExtensions(requiredExtensionsToBeInstalled)+ }+ if (installationCommand) {+ toast.loading(`Installing ${name}`, { id: toastId })+ await installationCommand({ ref: project.ref, track, ...values })+ }++ if (!!checkInstallationStatus) {+ const pollInstallationStatus = async () => {+ try {+ const { ref: projectRef, connectionString } = project || {}+ const status = await checkInstallationStatus({ projectRef, connectionString })+ if (status === 'installed') {+ toast.success(`Successfully installed ${name}`, { id: toastId })+ setOpen(false)+ setIsInstalling(false)+ } else {+ setTimeout(() => pollInstallationStatus(), 5000)+ }+ } catch (error) {+ toast.error(`Failed to install ${name}: ${(error as ResponseError).message}`, {+ id: toastId,+ })+ setIsInstalling(false)+ }+ }+ pollInstallationStatus()+ } else {+ toast.success(`Successfully installed ${name}`, { id: toastId })+ setOpen(false)+ setIsInstalling(false)+ }+ } catch (error) {+ toast.error(`Failed to install ${name}: ${(error as ResponseError).message}`, {+ id: toastId,+ })+ setIsInstalling(false)+ }+ }++ const installRequiredIntegrationExtensions = async (extensions: DatabaseExtension[]) => {+ if (!project) return console.error('Project is required')++ const { ref: projectRef, connectionString } = project+ const results = await Promise.allSettled(+ extensions.map((ext) => {+ const { name, default_version: version } = ext+ const createSchema = extensionsSchema[name].schema === 'custom'++ const defaultSchema = getExtensionDefaultSchema(ext)+ const schema =+ defaultSchema ||+ (createSchema ? (extensionsSchema[name].value as string) : extensionsSchema[name].schema)++ return enableExtension({+ projectRef,+ connectionString,+ schema,+ name,+ version,+ cascade: true,+ createSchema: createSchema || !schema.startsWith('pg_'),+ })+ })+ )++ const failure = results.find((r) => r.status === 'rejected')+ if (failure) throw new Error(failure.reason.message)+ }++ useEffect(() => {+ if (!isSuccessExtensions) return+ setExtensionsSchema(defaultExtensionsSchema)+ }, [isSuccessExtensions, defaultExtensionsSchema])++ return (+ <Sheet open={open} onOpenChange={setOpen}>+ <SheetTrigger asChild>+ <Button type="primary">Install integration</Button>+ </SheetTrigger>++ <Form_Shadcn_ {...form}>+ <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>+ <SheetContent+ size="default"+ aria-describedby={undefined}+ className="flex flex-col gap-0 !w-[650px]"+ >+ <SheetHeader className="flex items-center gap-x-4">+ <div className="shrink-0 w-11 h-11 relative bg-white border rounded-md flex items-center justify-center">+ {icon()}+ </div>+ <div className="flex flex-col">+ <SheetTitle>Install {name}</SheetTitle>+ <SheetDescription>Review and configure this integration</SheetDescription>+ </div>+ </SheetHeader>++ <div className="flex-grow overflow-y-auto">+ <div className="py-5 flex flex-col gap-y-7">+ {Object.keys(inputs).length > 0 && (+ <InstallationSettings form={form} integration={integration} />+ )}+ <InstallationOverview+ integration={integration}+ extensionsSchema={extensionsSchema}+ />+ </div>++ {allowExtensionCustomSchema && (+ <>+ <DialogSectionSeparator />+ <AdvancedSettings+ integration={integration}+ extensionsSchema={extensionsSchema}+ setExtensionsSchema={setExtensionsSchema}+ />+ </>+ )}++ <DialogSectionSeparator />+ </div>++ <SheetFooter>+ <SheetClose asChild>+ <Button type="default" disabled={isInstalling}>+ Cancel+ </Button>+ </SheetClose>+ <Button+ form={formId}+ htmlType="submit"+ type="primary"+ loading={isInstalling}+ disabled={hasMissingExtensions}+ >+ Install integration+ </Button>+ </SheetFooter>+ </SheetContent>+ </form>+ </Form_Shadcn_>+ </Sheet>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallationOverview.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallationOverview.tsxnew file mode 100644index 00000000000..85ee813bb93--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallationOverview.tsx@@ -0,0 +1,137 @@+import { Markdown } from 'components/interfaces/Markdown'+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'+import {+ Badge,+ Card,+ CardContent,+ cn,+ SheetSection,+ Tabs_Shadcn_,+ TabsContent_Shadcn_,+ TabsList_Shadcn_,+ TabsTrigger_Shadcn_,+} from 'ui'+import { CodeBlock } from 'ui-patterns/CodeBlock'++import { getEnableExtensionsSQL } from '../IntegrationOverviewTabV2.utils'+import { type ExtensionsSchema, type InstallIntegrationSheetProps } from './InstallIntegrationSheet'++export const InstallationOverview = ({+ integration,+ extensionsSchema,+}: InstallIntegrationSheetProps & { extensionsSchema: ExtensionsSchema }) => {+ const { data: project } = useSelectedProjectQuery()++ const {+ steps = [],+ installationSql,+ missingExtensionsAlert,+ requiredExtensions: requiredExtensionNames,+ } = integration++ const involvesExtensions = requiredExtensionNames.length > 0+ // [Joshen] Will hook these up in the future, applicable for stripe sync engine+ const involvesEdgeFunctions = false++ const { data: extensions = [] } = useDatabaseExtensionsQuery(+ { projectRef: project?.ref, connectionString: project?.connectionString },+ { enabled: involvesExtensions }+ )+ const requiredExtensions = extensions.filter((ext) => requiredExtensionNames.includes(ext.name))++ const enableExtensionsSQL = getEnableExtensionsSQL({+ extensions: requiredExtensions.filter((ext) => !ext.installed_version),+ extensionsSchema,+ })+ const installationSQLContent = installationSql ?? enableExtensionsSQL++ // [Joshen] Integration requires extensions that are not available to install on the current database image+ const hasMissingExtensions = requiredExtensionNames.length !== requiredExtensions.length++ return (+ <SheetSection className="flex flex-col gap-y-4 py-0">+ <div>+ <h4>Installs</h4>+ <p className="text-sm text-foreground-light">+ What this integration will run on your project+ </p>+ </div>++ {hasMissingExtensions && missingExtensionsAlert}++ {steps.length > 0 && (+ <Card>+ <CardContent className="p-0">+ <ul className="text-foreground-light text-sm divide-y">+ {steps.map((step) => (+ <li key={step.label} className="px-4 py-2">+ <Markdown>{step.label}</Markdown>+ </li>+ ))}+ </ul>+ </CardContent>+ </Card>+ )}++ <Card>+ <CardContent className="px-0 pt-1.5 pb-0">+ <Tabs_Shadcn_ defaultValue="extensions">+ <TabsList_Shadcn_ className="px-4 space-x-4">+ {involvesExtensions && (+ <>+ <TabsTrigger_Shadcn_ value="extensions" className="font-mono uppercase text-xs">+ Extensions+ </TabsTrigger_Shadcn_>+ <TabsTrigger_Shadcn_ value="sql" className="font-mono uppercase text-xs">+ SQL+ </TabsTrigger_Shadcn_>+ </>+ )}+ {involvesEdgeFunctions && (+ <TabsTrigger_Shadcn_ value="edge_functions" className="font-mono uppercase text-xs">+ Edge Functions+ </TabsTrigger_Shadcn_>+ )}+ </TabsList_Shadcn_>++ <TabsContent_Shadcn_ value="extensions" className="mt-0 divide-y">+ {requiredExtensionNames.map((extName) => {+ const ext = extensions.find((x) => x.name === extName)+ return (+ <div key={extName} className="py-3 px-4 flex items-center justify-between">+ <code className="text-xs">{extName}</code>+ {!ext ? (+ <Badge variant="warning">Unavailable</Badge>+ ) : ext.installed_version ? (+ <Badge variant="secondary" className="text-foreground-lighter">+ Installed+ </Badge>+ ) : (+ <Badge variant="default" className="text-foreground">+ Required+ </Badge>+ )}+ </div>+ )+ })}+ </TabsContent_Shadcn_>+ <TabsContent_Shadcn_ value="sql" className="mt-0">+ <CodeBlock+ hideCopy+ hideLineNumbers+ language="pgsql"+ value={installationSQLContent}+ wrapperClassName={cn('[&_pre]:px-4 [&_pre]:py-3')}+ className="border-0 rounded-none [&_code]:text-[12px] [&_code]:text-foreground max-h-80"+ />+ </TabsContent_Shadcn_>+ <TabsContent_Shadcn_ value="edge_functions" className="mt-0">+ TBD+ </TabsContent_Shadcn_>+ </Tabs_Shadcn_>+ </CardContent>+ </Card>+ </SheetSection>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallationSettings.tsx b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallationSettings.tsxnew file mode 100644index 00000000000..b2c2f793b54--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallationSettings.tsx@@ -0,0 +1,86 @@+import { ExternalLink } from 'lucide-react'+import Link from 'next/link'+import { UseFormReturn } from 'react-hook-form'+import { Button, Card, CardContent, FormControl_Shadcn_, FormField_Shadcn_, SheetSection } from 'ui'+import { Input } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import { type InstallIntegrationSheetProps } from './InstallIntegrationSheet'++export const InstallationSettings = ({+ integration,+ form,+}: InstallIntegrationSheetProps & {+ form: UseFormReturn<Record<string, string>, unknown, undefined>+}) => {+ const { inputs = {} } = integration++ return (+ <SheetSection className="flex flex-col gap-y-4 py-0">+ <div>+ <h4>Settings</h4>+ <p className="text-sm text-foreground-light">Configure the integration</p>+ </div>++ <Card>+ <CardContent className="divide-y p-0">+ {Object.entries(inputs).map((entry) => {+ const [key, input] = entry+ const { type, label, description, required, actions = [] } = input++ return (+ <div key={key} className="flex flex-col gap-y-2 p-4">+ <FormField_Shadcn_+ key={key}+ name={key}+ control={form.control}+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ isReactForm={false}+ name={key}+ label={label}+ description={description}+ >+ <FormControl_Shadcn_>+ <Input+ type={type}+ placeholder={required ? 'Provide a value' : undefined}+ {...field}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ {actions.length > 0 && (+ <div className="flex items-center gap-x-2">+ {actions.map((action) => {+ const isExternal = action.href.startsWith('https')+ return (+ <Button+ asChild+ key={action.label}+ type="default"+ icon={isExternal ? <ExternalLink /> : undefined}+ >+ <Link+ href={action.href}+ target={isExternal ? '_blank' : undefined}+ rel={isExternal ? 'noopener noreferrer' : undefined}+ >+ {action.label}+ </Link>+ </Button>+ )+ })}+ </div>+ )}+ </div>+ )+ })}+ </CardContent>+ </Card>+ </SheetSection>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx b/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsxindex 20d0406f8d3..4754962cd6c 100644--- a/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx+++ b/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx@@ -1,4 +1,8 @@import { getEnableWebhooksSQL } from '@supabase/pg-meta'+import { stripeSyncKeys } from 'data/database-integrations/stripe/keys'+import { installStripeSync } from 'data/database-integrations/stripe/stripe-sync-install-mutation'+import { databaseKeys } from 'data/database/keys'+import { useTrack } from 'lib/telemetry/track'import { Clock5, Code2, Layers, Timer, Vault, Webhook } from 'lucide-react'import dynamic from 'next/dynamic'import Image from 'next/image'@@ -7,10 +11,11 @@ import { cn } from 'ui'import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import { UpgradeDatabaseAlert } from '../Queues/UpgradeDatabaseAlert'+import { getStripeSyncSchemaComment } from '../templates/StripeSyncEngine/useStripeSyncStatus'import { WRAPPERS } from '../Wrappers/Wrappers.constants'import { WrapperMeta } from '../Wrappers/Wrappers.types'import { enableDatabaseWebhooks } from '@/data/database/hooks-enable-mutation'-import { invalidateSchemasQuery } from '@/data/database/schemas-query'+import { getSchemas, invalidateSchemasQuery } from '@/data/database/schemas-query'import { getQueryClient } from '@/data/query-client'import { BASE_PATH, DOCS_URL } from '@/lib/constants'@@ -22,12 +27,29 @@ export type Navigation = {children?: Navigation[]}-export const Loading = () => (- <div className="p-10">- <GenericSkeletonLoader />- </div>-)+// [Joshen] Basing this on template.json for now+export type IntegrationInputs = {+ [key: string]: {+ label: string+ type: 'text' | 'number' | 'password'+ description?: string+ required: boolean+ actions: {+ label: string+ href: string+ }[]+ }+}+type IntegrationStep = {+ label: string+ description?: string+}++/**+ * [Joshen] For marketplace, we probably need to revisit this definition+ * What properties are obsolete, what properties we need from remote source+ */export type IntegrationDefinition = {id: stringname: string@@ -52,10 +74,29 @@ export type IntegrationDefinition = {pageId: string | undefinedchildId: string | undefined}) => ComponentType<{}> | null- /** SQL query for installing the entire integration */++ /** For showing the SQL query in the installation sheet */installationSql?: string- /** Custom command to install the integration */- installationCommand?: (props: { ref: string }) => Promise<void>+ /** Custom command to install the integration (if any - none atm) */+ installationCommand?: (props: {+ ref: string+ track?: ReturnType<typeof useTrack>+ [key: string]: unknown+ }) => Promise<void>+ /**+ * Used for long polling to track the progress of the integration installation if async+ * The component calling this handles the polling logic, and should terminate the poll depending on the returned value+ * Depending on how we want this to work, this method will thereafter also call any RQ invalidation if required+ * */+ checkInstallationStatus?: (props: {+ ref?: string+ connectionString?: string | null+ [key: string]: unknown+ }) => Promise<'installed' | 'installing'>+ /** User inputs for template integrations */+ inputs?: IntegrationInputs+ /** Purely visual, just to show what are the changes on the project from installing the integration */+ steps?: IntegrationStep[]} & (| { type: 'wrapper'; meta: WrapperMeta }| { type: 'postgres_extension' | 'custom' | 'oauth' | 'template' }@@ -451,7 +492,7 @@ const WRAPPER_INTEGRATIONS: Array<IntegrationDefinition> = WRAPPERS.map((w) => {const TEMPLATE_INTEGRATIONS: Array<IntegrationDefinition> = [{id: 'stripe_sync_engine',- type: 'custom' as const,+ type: 'template' as const,requiredExtensions: ['pgmq', 'supabase_vault', 'pg_cron', 'pg_net'],missingExtensionsAlert: <UpgradeDatabaseAlert minimumVersion="15.6.1.143" />,name: `Stripe Sync Engine`,@@ -487,8 +528,8 @@ const TEMPLATE_INTEGRATIONS: Array<IntegrationDefinition> = [case 'overview':return dynamic(() =>- import('@/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationOverview').then(- (mod) => mod.StripeSyncInstallationPage+ import('components/interfaces/Integrations/templates/StripeSyncEngine/OverviewTab').then(+ (mod) => mod.StripeSyncEngineOverviewTab),{ loading: Loading })@@ -503,6 +544,62 @@ const TEMPLATE_INTEGRATIONS: Array<IntegrationDefinition> = [}return null},+ inputs: {+ stripe_api_key: {+ type: 'password',+ required: true,+ label: 'Stripe API secret key',+ description:+ 'Requires write access to Webhook Endpoints and read-only access to all other categories.',+ actions: [+ {+ label: 'Get API key',+ href: 'https://dashboard.stripe.com/apikeys',+ },+ {+ label: 'What are Stripe API keys?',+ href: 'https://support.stripe.com/questions/what-are-stripe-api-keys-and-how-to-find-them',+ },+ ],+ },+ },+ steps: [+ { label: 'Creates a new database schema named `stripe`' },+ { label: 'Creates tables and views in the `stripe` schema for synced Stripe data' },+ { label: 'Deploys Edge Functions to handle incoming webhooks from Stripe' },+ { label: 'Schedules automatic Stripe data syncs using Supabase Queues' },+ ],+ installationCommand: async ({ ref: projectRef, track, stripe_api_key }) => {+ const startTime = Date.now()+ await installStripeSync({ projectRef, startTime, stripeSecretKey: stripe_api_key as string })++ if (track) track('integration_install_submitted', { integrationName: 'stripe_sync_engine' })++ const queryClient = getQueryClient()+ await queryClient.invalidateQueries({ queryKey: stripeSyncKeys.all })+ },+ checkInstallationStatus: async (props) => {+ const queryClient = getQueryClient()+ const { projectRef, connectionString } = props || {}++ const schemas = await getSchemas({+ projectRef: projectRef as string,+ connectionString: connectionString as string,+ })++ const { status, errorMessage } = getStripeSyncSchemaComment(schemas)++ if (status === 'install error') {+ throw new Error(errorMessage ?? 'Stripe Sync installation failed')+ }++ if (status === 'installed') {+ await queryClient.invalidateQueries({+ queryKey: databaseKeys.schemas(projectRef as string),+ })+ }+ return status === 'installed' ? 'installed' : 'installing'+ },},]@@ -511,3 +608,9 @@ export const INTEGRATIONS: Array<IntegrationDefinition> = [...SUPABASE_INTEGRATIONS,...TEMPLATE_INTEGRATIONS,]++export const Loading = () => (+ <div className="p-10">+ <GenericSkeletonLoader />+ </div>+)diff --git a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationError.tsx b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationError.tsxindex 90bf85d1f8f..8301cdc5ceb 100644--- a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationError.tsx+++ b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationError.tsx@@ -20,14 +20,9 @@ export const InstallationError = ({installing?: booleanuninstalling?: boolean}) => {- const { data: project } = useSelectedProjectQuery()-const {schemaComment: { errorMessage },- } = useStripeSyncStatus({- projectRef: project?.ref,- connectionString: project?.connectionString,- })+ } = useStripeSyncStatus()if (error === 'uninstall') {return (diff --git a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationOverview.tsx b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationOverview.tsxdeleted file mode 100644index 22d5e73d670..00000000000--- a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/InstallationOverview.tsx+++ /dev/null@@ -1,453 +0,0 @@-import { zodResolver } from '@hookform/resolvers/zod'-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { ExternalLink } from 'lucide-react'-import Link from 'next/link'-import { useCallback, useEffect, useRef, useState } from 'react'-import { useForm } from 'react-hook-form'-import { toast } from 'sonner'-import {- Button,- Form_Shadcn_,- FormControl_Shadcn_,- FormField_Shadcn_,- Sheet,- SheetContent,- SheetFooter,- SheetHeader,- SheetSection,- SheetTitle,-} from 'ui'-import { Admonition } from 'ui-patterns'-import { Input } from 'ui-patterns/DataInputs/Input'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'-import * as z from 'zod'--import { IntegrationOverviewTab } from '../../Integration/IntegrationOverviewTab'-import { InstallationError } from './InstallationError'-import { StatusDisplay } from './StatusDisplay'-import {- canInstall as checkCanInstall,- hasInstallError,- hasUninstallError,- isInstallDone,- isInstalled,- isInstalling,- isUninstallDone,- isUninstalling,-} from './stripe-sync-status'-import { StripeSyncChangesCard } from './StripeSyncChangesCard'-import { useStripeSyncStatus } from '@/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus'-import { ButtonTooltip } from '@/components/ui/ButtonTooltip'-import { useStripeSyncInstallMutation } from '@/data/database-integrations/stripe/stripe-sync-install-mutation'-import { useStripeSyncUninstallMutation } from '@/data/database-integrations/stripe/stripe-sync-uninstall-mutation'-import { useSchemasQuery } from '@/data/database/schemas-query'-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'-import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'-import { useTrack } from '@/lib/telemetry/track'--const installFormSchema = z.object({- stripeSecretKey: z.string().min(1, 'Stripe API key is required'),-})--export const StripeSyncInstallationPage = () => {- const track = useTrack()- const hasTrackedInstallFailed = useRef(false)- const { data: project } = useSelectedProjectQuery()-- const [shouldShowInstallSheet, setShouldShowInstallSheet] = useState(false)- const [showUninstallModal, setShowUninstallModal] = useState(false)- // These flags bridge the gap between mutation success and schema update- const [isInstallInitiated, setIsInstallInitiated] = useState(false)- const [isUninstallInitiated, setIsUninstallInitiated] = useState(false)-- const formId = 'stripe-sync-install-form'- const form = useForm<z.infer<typeof installFormSchema>>({- resolver: zodResolver(installFormSchema),- defaultValues: { stripeSecretKey: '' },- mode: 'onSubmit',- })-- const {- schemaComment,- schemaComment: { status: installationStatus },- latestAvailableVersion,- timedOut,- } = useStripeSyncStatus({- projectRef: project?.ref,- connectionString: project?.connectionString,- })-- // Check permissions for managing function secrets- const { can: canManageSecrets } = useAsyncCheckPermissions(- PermissionAction.FUNCTIONS_SECRET_WRITE,- '*'- )-- const installed = isInstalled(installationStatus)- const installError = hasInstallError(installationStatus)- const uninstallError = hasUninstallError(installationStatus)- const installInProgress = isInstalling(installationStatus)- const uninstallInProgress = isUninstalling(installationStatus)- const installDone = isInstallDone(installationStatus)- const uninstallDone = isUninstallDone(installationStatus)-- // Detect if this is an upgrade (both old and new versions present)- let oldVersion- let newVersion- if (installed) {- // when installed we compare the installed version against the latest available- oldVersion = schemaComment?.newVersion- newVersion = latestAvailableVersion- } else {- // otherwise compare the old and new versions from the schema- oldVersion = schemaComment?.oldVersion- newVersion = schemaComment?.newVersion- }-- const upgradeAvailable = !!(oldVersion && newVersion && oldVersion !== newVersion)- const upgradeDone = latestAvailableVersion == schemaComment?.newVersion-- const {- mutate: installStripeSync,- isPending: isInstallRequested,- error: installRequestError,- reset: resetInstallError,- } = useStripeSyncInstallMutation({- onSuccess: () => {- toast.success(- upgradeAvailable ? 'Stripe Sync upgrade started' : 'Stripe Sync installation started'- )- setShouldShowInstallSheet(false)- form.reset()- setIsInstallInitiated(true)- },- })-- const { mutate: uninstallStripeSync, isPending: isUninstallRequested } =- useStripeSyncUninstallMutation({- onSuccess: () => {- toast.success('Stripe Sync uninstallation started')- setShowUninstallModal(false)- setIsUninstallInitiated(true)- },- })-- // Combine schema status with mutation/initiated states for UI- const installing = (installInProgress || isInstallRequested || isInstallInitiated) && !timedOut- const uninstalling =- (uninstallInProgress || isUninstallRequested || isUninstallInitiated) && !timedOut- const canInstall = checkCanInstall(installationStatus) && !installed && !installing-- const hasError = (uninstallError || installError) && ((!uninstalling && !installing) || timedOut)-- // Poll for schema changes during transitions- useSchemasQuery(- { projectRef: project?.ref, connectionString: project?.connectionString },- { refetchInterval: installing || uninstalling ? 5000 : false }- )-- const handleUninstall = useCallback(() => {- if (!project?.ref) return-- uninstallStripeSync({- projectRef: project.ref,- startTime: Date.now(),- })- }, [project?.ref, uninstallStripeSync])-- const handleOpenInstallSheet = useCallback(() => {- resetInstallError()- setShouldShowInstallSheet(true)- }, [resetInstallError])-- const handleCloseInstallSheet = (isOpen: boolean) => {- if (isInstallRequested) return-- setShouldShowInstallSheet(isOpen)- if (!isOpen) {- form.reset()- resetInstallError()- }- }-- // Track install failures- useEffect(() => {- if (!installError) {- hasTrackedInstallFailed.current = false- return- }-- if (!hasTrackedInstallFailed.current) {- hasTrackedInstallFailed.current = true- track('integration_install_failed', {- integrationName: 'stripe_sync_engine',- })- }- }, [installError, track])-- // Clear install initiated flag once schema reflects successful completion- // For errors, the flag is cleared when user manually retries (handleOpenInstallSheet)- useEffect(() => {- if (isInstallInitiated && installDone && upgradeDone && !installError) {- setIsInstallInitiated(false)- }- }, [isInstallInitiated, installDone, upgradeDone, installError])-- // Clear uninstall initiated flag once schema is removed or error- useEffect(() => {- if (isUninstallInitiated && uninstallDone) {- setIsUninstallInitiated(false)- }- }, [isUninstallInitiated, uninstallDone])-- return (- <IntegrationOverviewTab- alert={- hasError ? (- <InstallationError- error={uninstallError ? 'uninstall' : 'install'}- handleUninstall={handleUninstall}- handleOpenInstallSheet={handleOpenInstallSheet}- isUpgrade={upgradeAvailable}- installing={installing}- uninstalling={uninstalling}- />- ) : null- }- status={- <StatusDisplay- status={installationStatus}- isInstallRequested={isInstallRequested}- isInstallInitiated={isInstallInitiated}- isUninstallRequested={isUninstallRequested}- isUninstallInitiated={isUninstallInitiated}- isUpgrade={upgradeAvailable}- timedOut={timedOut}- />- }- actions={- !installed && !uninstalling && !uninstallError ? (- <>- <StripeSyncChangesCard- installationStatus={installationStatus}- isUpgrade={upgradeAvailable}- />- <div className="flex gap-x-2 justify-end mt-4">- <ButtonTooltip- type="primary"- onClick={() => setShouldShowInstallSheet(true)}- disabled={!canInstall || !canManageSecrets}- loading={installing}- tooltip={{- content: {- text: !canInstall- ? 'Your database already uses a schema named "stripe"'- : !canManageSecrets- ? 'You need additional permissions to install the Stripe Sync Engine.'- : undefined,- },- }}- >- {installError- ? upgradeAvailable- ? 'Retry upgrade'- : 'Retry installation'- : upgradeAvailable- ? 'Upgrade integration'- : 'Install integration'}- </ButtonTooltip>- {installError && (- <Button type="default" loading={isUninstallRequested} onClick={handleUninstall}>- Uninstall- </Button>- )}- </div>- </>- ) : installed || uninstalling || uninstallError ? (- <>- <StripeSyncChangesCard- installationStatus={installationStatus}- isUpgrade={upgradeAvailable}- />- <div className="flex gap-x-2 justify-end mt-4">- {upgradeAvailable && !uninstallError && !uninstalling && (- <ButtonTooltip- type="primary"- onClick={() => setShouldShowInstallSheet(true)}- disabled={installing || !canManageSecrets}- loading={installing}- tooltip={{- content: {- text: !canManageSecrets- ? 'You need additional permissions to upgrade the Stripe Sync Engine.'- : undefined,- },- }}- >- Upgrade integration- </ButtonTooltip>- )}- <ButtonTooltip- type="default"- onClick={() => setShowUninstallModal(true)}- disabled={installing || uninstalling || !canManageSecrets}- loading={uninstalling}- tooltip={{- content: {- text: !canManageSecrets- ? 'You need additional permissions to uninstall the Stripe Sync Engine.'- : undefined,- },- }}- >- {uninstallError ? 'Retry uninstallation' : 'Uninstall integration'}- </ButtonTooltip>- </div>- </>- ) : null- }- >- <Sheet open={!!shouldShowInstallSheet} onOpenChange={handleCloseInstallSheet}>- <SheetContent size="lg" tabIndex={undefined} className="flex flex-col gap-0">- <Form_Shadcn_ {...form}>- <form- id={formId}- onSubmit={form.handleSubmit(({ stripeSecretKey }) => {- if (!project?.ref) return- installStripeSync({- projectRef: project.ref,- stripeSecretKey,- startTime: Date.now(),- })- })}- className="overflow-auto flex-grow px-0 flex flex-col"- >- <SheetHeader>- <SheetTitle>- {upgradeAvailable ? 'Upgrade' : 'Install'} Stripe Sync Engine- </SheetTitle>- </SheetHeader>- <SheetSection className="flex-1 flex flex-col gap-y-6">- <StripeSyncChangesCard- installationStatus={installationStatus}- isUpgrade={upgradeAvailable}- />-- <h3 className="heading-default">Configuration</h3>-- <div className="flex flex-col gap-y-2">- <FormField_Shadcn_- control={form.control}- name="stripeSecretKey"- render={({ field }) => (- <FormItemLayout- layout="flex-row-reverse"- label="Stripe API secret key"- description="Your Stripe secret key. Requires write access to Webhook Endpoints and read-only access to all other categories."- >- <FormControl_Shadcn_ className="col-span-8">- <Input- id="stripe_api_key"- name="stripe_api_key"- placeholder="Enter your Stripe API key"- autoComplete="stripe-api-key"- reveal={false}- disabled={isInstallRequested}- type="password"- value={field.value}- onChange={(e) => field.onChange(e.target.value)}- />- </FormControl_Shadcn_>- </FormItemLayout>- )}- />-- <div className="flex items-center gap-x-2">- <Button asChild type="default" icon={<ExternalLink />}>- <Link- target="_blank"- rel="noopener noreferrer"- href="https://dashboard.stripe.com/apikeys"- >- Get Stripe API key- </Link>- </Button>- <Button asChild type="default" icon={<ExternalLink />}>- <Link- target="_blank"- rel="noopener noreferrer"- href="https://support.stripe.com/questions/what-are-stripe-api-keys-and-how-to-find-them"- >- What are Stripe API keys?- </Link>- </Button>- </div>- </div>-- {installRequestError && (- <Admonition- type="destructive"- title="Installation failed"- description={installRequestError.message}- />- )}- </SheetSection>-- <SheetFooter>- <Button- type="default"- disabled={isInstallRequested}- onClick={() => handleCloseInstallSheet(false)}- >- Cancel- </Button>- <Button- form={formId}- htmlType="submit"- type="primary"- loading={isInstallRequested}- disabled={!form.formState.isValid || isInstallRequested}- >- {isInstallRequested- ? upgradeAvailable- ? 'Upgrading'- : 'Installing'- : upgradeAvailable- ? 'Upgrade integration'- : 'Install integration'}- </Button>- </SheetFooter>- </form>- </Form_Shadcn_>- </SheetContent>- </Sheet>-- <ConfirmationModal- visible={showUninstallModal}- title="Uninstall Stripe Sync Engine"- confirmLabel="Uninstall"- confirmLabelLoading="Uninstalling..."- variant="destructive"- loading={isUninstallRequested}- onCancel={() => setShowUninstallModal(false)}- onConfirm={handleUninstall}- >- <p className="text-sm text-foreground-light">- Are you sure you want to uninstall the Stripe Sync Engine? This will:- </p>- <ul className="list-disc pl-5 mt-2 text-sm text-foreground-light space-y-1">- <li>- Remove the <code className="text-code-inline">stripe</code> schema and all tables- </li>- <li>Delete all synced Stripe data</li>- <li>Remove the associated Edge Functions</li>- <li>Remove the scheduled sync jobs</li>- </ul>- <p className="mt-4 text-sm text-foreground-light font-medium">- This action cannot be undone.- </p>- </ConfirmationModal>- </IntegrationOverviewTab>- )-}diff --git a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/IntegrationActions.tsx b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/IntegrationActions.tsxnew file mode 100644index 00000000000..98694e06b94--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/IntegrationActions.tsx@@ -0,0 +1,132 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Button, cn } from 'ui'++import { hasInstallError, hasUninstallError } from './stripe-sync-status'+import { useStripeSyncStatus } from '@/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'++export const IntegrationInstalledActions = ({+ className,+ disabled,+ upgradeAvailable,+ installing,+ uninstalling,+ setShowUninstallModal,+ setShouldShowInstallSheet,+}: {+ className?: string+ disabled?: boolean+ upgradeAvailable: boolean+ installing: boolean+ uninstalling: boolean+ isUninstallRequested: boolean+ setShowUninstallModal: (value: boolean) => void+ setShouldShowInstallSheet: (value: boolean) => void+}) => {+ const { can: canManageSecrets } = useAsyncCheckPermissions(+ PermissionAction.FUNCTIONS_SECRET_WRITE,+ '*'+ )++ const {+ schemaComment: { status: installationStatus },+ } = useStripeSyncStatus()+ const uninstallError = hasUninstallError(installationStatus)++ return (+ <>+ <div className={cn('flex gap-x-2 justify-end', className)}>+ {upgradeAvailable && !uninstallError && !uninstalling && (+ <ButtonTooltip+ type="primary"+ onClick={() => setShouldShowInstallSheet(true)}+ disabled={disabled}+ loading={installing}+ tooltip={{+ content: {+ text: !canManageSecrets+ ? 'You need additional permissions to upgrade the Stripe Sync Engine.'+ : undefined,+ },+ }}+ >+ Upgrade integration+ </ButtonTooltip>+ )}+ <ButtonTooltip+ type="default"+ onClick={() => setShowUninstallModal(true)}+ disabled={disabled}+ loading={uninstalling}+ tooltip={{+ content: {+ text: !canManageSecrets+ ? 'You need additional permissions to uninstall the Stripe Sync Engine.'+ : undefined,+ },+ }}+ >+ {uninstallError ? 'Retry uninstallation' : 'Uninstall integration'}+ </ButtonTooltip>+ </div>+ </>+ )+}++export const IntegrationNotInstalledActions = ({+ className,+ installing,+ canInstall,+ isUninstallRequested,+ hideInstallCTA = false,+ handleUninstall,+ setShouldShowInstallSheet,+}: {+ className?: string+ installing: boolean+ canInstall: boolean+ isUninstallRequested: boolean+ hideInstallCTA?: boolean+ handleUninstall: () => void+ setShouldShowInstallSheet: (value: boolean) => void+}) => {+ const { can: canManageSecrets } = useAsyncCheckPermissions(+ PermissionAction.FUNCTIONS_SECRET_WRITE,+ '*'+ )++ const {+ schemaComment: { status: installationStatus },+ } = useStripeSyncStatus()+ const installError = hasInstallError(installationStatus)++ return (+ <div className={cn('flex gap-x-2 justify-end', className)}>+ {!hideInstallCTA && (+ <ButtonTooltip+ type="primary"+ onClick={() => setShouldShowInstallSheet(true)}+ disabled={!canInstall || !canManageSecrets}+ loading={installing}+ tooltip={{+ content: {+ text: !canInstall+ ? 'Your database already uses a schema named "stripe"'+ : !canManageSecrets+ ? 'You need additional permissions to install the Stripe Sync Engine.'+ : undefined,+ },+ }}+ >+ {installError ? 'Retry installation' : 'Install integration'}+ </ButtonTooltip>+ )}+ {installError && (+ <Button type="default" loading={isUninstallRequested} onClick={handleUninstall}>+ Uninstall+ </Button>+ )}+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/OverviewTab.tsx b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/OverviewTab.tsxnew file mode 100644index 00000000000..54c36bbbf77--- /dev/null+++ b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/OverviewTab.tsx@@ -0,0 +1,446 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useFlag } from 'common'+import { ExternalLink } from 'lucide-react'+import Link from 'next/link'+import { useCallback, useEffect, useRef, useState } from 'react'+import { useForm } from 'react-hook-form'+import { toast } from 'sonner'+import {+ Button,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetSection,+ SheetTitle,+} from 'ui'+import { Admonition } from 'ui-patterns'+import { Input } from 'ui-patterns/DataInputs/Input'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import * as z from 'zod'++import { IntegrationOverviewTab } from '../../Integration/IntegrationOverviewTab'+import { IntegrationOverviewTabV2 } from '../../Integration/IntegrationOverviewTabV2'+import { InstallationError } from './InstallationError'+import { IntegrationInstalledActions, IntegrationNotInstalledActions } from './IntegrationActions'+import { StatusDisplay } from './StatusDisplay'+import {+ canInstall as checkCanInstall,+ hasInstallError,+ hasUninstallError,+ isInstallDone,+ isInstalled,+ isInstalling,+ isUninstallDone,+ isUninstalling,+} from './stripe-sync-status'+import { StripeSyncChangesCard } from './StripeSyncChangesCard'+import { useStripeSyncStatus } from '@/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus'+import { useStripeSyncInstallMutation } from '@/data/database-integrations/stripe/stripe-sync-install-mutation'+import { useStripeSyncUninstallMutation } from '@/data/database-integrations/stripe/stripe-sync-uninstall-mutation'+import { useSchemasQuery } from '@/data/database/schemas-query'+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { useTrack } from '@/lib/telemetry/track'++const installFormSchema = z.object({+ stripeSecretKey: z.string().min(1, 'Stripe API key is required'),+})++export const StripeSyncEngineOverviewTab = () => {+ const track = useTrack()+ const hasTrackedInstallFailed = useRef(false)+ const { data: project } = useSelectedProjectQuery()+ const isMarketplaceEnabled = useFlag('marketplaceIntegrations')++ const [showUninstallModal, setShowUninstallModal] = useState(false)+ const [shouldShowInstallSheet, setShouldShowInstallSheet] = useState(false)+ // These flags bridge the gap between mutation success and schema update+ const [isInstallInitiated, setIsInstallInitiated] = useState(false)+ const [isUninstallInitiated, setIsUninstallInitiated] = useState(false)++ const formId = 'stripe-sync-install-form'+ const form = useForm<z.infer<typeof installFormSchema>>({+ resolver: zodResolver(installFormSchema),+ defaultValues: { stripeSecretKey: '' },+ mode: 'onSubmit',+ })++ const {+ schemaComment,+ schemaComment: { status: installationStatus },+ latestAvailableVersion,+ timedOut,+ } = useStripeSyncStatus()++ // Check permissions for managing function secrets+ const { can: canManageSecrets } = useAsyncCheckPermissions(+ PermissionAction.FUNCTIONS_SECRET_WRITE,+ '*'+ )++ const installed = isInstalled(installationStatus)+ const installError = hasInstallError(installationStatus)+ const uninstallError = hasUninstallError(installationStatus)+ const installInProgress = isInstalling(installationStatus)+ const uninstallInProgress = isUninstalling(installationStatus)+ const installDone = isInstallDone(installationStatus)+ const uninstallDone = isUninstallDone(installationStatus)++ // Detect if this is an upgrade (both old and new versions present)+ let oldVersion+ let newVersion+ if (installed) {+ // when installed we compare the installed version against the latest available+ oldVersion = schemaComment?.newVersion+ newVersion = latestAvailableVersion+ } else {+ // otherwise compare the old and new versions from the schema+ oldVersion = schemaComment?.oldVersion+ newVersion = schemaComment?.newVersion+ }++ const upgradeAvailable = !!(oldVersion && newVersion && oldVersion !== newVersion)+ const upgradeDone = latestAvailableVersion == schemaComment?.newVersion++ const {+ mutate: installStripeSync,+ isPending: isInstallRequested,+ error: installRequestError,+ reset: resetInstallError,+ } = useStripeSyncInstallMutation({+ onSuccess: () => {+ toast.success(+ upgradeAvailable ? 'Stripe Sync upgrade started' : 'Stripe Sync installation started'+ )+ setShouldShowInstallSheet(false)+ form.reset()+ setIsInstallInitiated(true)+ },+ })++ const { mutate: uninstallStripeSync, isPending: isUninstallRequested } =+ useStripeSyncUninstallMutation({+ onSuccess: () => {+ toast.success('Stripe Sync uninstallation started')+ setShowUninstallModal(false)+ setIsUninstallInitiated(true)+ },+ })++ // Combine schema status with mutation/initiated states for UI+ const installing = (installInProgress || isInstallRequested || isInstallInitiated) && !timedOut+ const uninstalling =+ (uninstallInProgress || isUninstallRequested || isUninstallInitiated) && !timedOut+ const canInstall = checkCanInstall(installationStatus) && !installed && !installing++ const hasError = (uninstallError || installError) && ((!uninstalling && !installing) || timedOut)++ // Poll for schema changes during transitions+ useSchemasQuery(+ { projectRef: project?.ref, connectionString: project?.connectionString },+ { refetchInterval: installing || uninstalling ? 5000 : false }+ )++ const handleUninstall = useCallback(() => {+ if (!project?.ref) return++ uninstallStripeSync({+ projectRef: project.ref,+ startTime: Date.now(),+ })+ }, [project?.ref, uninstallStripeSync])++ const handleOpenInstallSheet = useCallback(() => {+ resetInstallError()+ setShouldShowInstallSheet(true)+ }, [resetInstallError])++ const handleCloseInstallSheet = (isOpen: boolean) => {+ if (isInstallRequested) return++ setShouldShowInstallSheet(isOpen)+ if (!isOpen) {+ form.reset()+ resetInstallError()+ }+ }++ // Track install failures+ useEffect(() => {+ if (!installError) {+ hasTrackedInstallFailed.current = false+ return+ }++ if (!hasTrackedInstallFailed.current) {+ hasTrackedInstallFailed.current = true+ track('integration_install_failed', {+ integrationName: 'stripe_sync_engine',+ })+ }+ }, [installError, track])++ // Clear install initiated flag once schema reflects successful completion+ // For errors, the flag is cleared when user manually retries (handleOpenInstallSheet)+ useEffect(() => {+ if (isInstallInitiated && installDone && upgradeDone && !installError) {+ setIsInstallInitiated(false)+ }+ }, [isInstallInitiated, installDone, upgradeDone, installError])++ // Clear uninstall initiated flag once schema is removed or error+ useEffect(() => {+ if (isUninstallInitiated && uninstallDone) {+ setIsUninstallInitiated(false)+ }+ }, [isUninstallInitiated, uninstallDone])++ return (+ <>+ {isMarketplaceEnabled ? (+ <IntegrationOverviewTabV2>+ {hasError && (+ <InstallationError+ error={uninstallError ? 'uninstall' : 'install'}+ handleUninstall={handleUninstall}+ handleOpenInstallSheet={handleOpenInstallSheet}+ isUpgrade={upgradeAvailable}+ installing={installing}+ uninstalling={uninstalling}+ />+ )}++ {!installed && !uninstalling && !uninstallError ? (+ <IntegrationNotInstalledActions+ hideInstallCTA+ installing={installing}+ canInstall={canInstall}+ isUninstallRequested={isUninstallRequested}+ handleUninstall={handleUninstall}+ setShouldShowInstallSheet={setShouldShowInstallSheet}+ />+ ) : (+ (installed || uninstalling || uninstallError) && (+ <IntegrationInstalledActions+ disabled={installing || uninstalling || !canManageSecrets}+ upgradeAvailable={upgradeAvailable}+ installing={installing}+ uninstalling={uninstalling}+ isUninstallRequested={isUninstallRequested}+ setShouldShowInstallSheet={setShouldShowInstallSheet}+ setShowUninstallModal={setShowUninstallModal}+ />+ )+ )}+ </IntegrationOverviewTabV2>+ ) : (+ <IntegrationOverviewTab+ alert={+ hasError ? (+ <InstallationError+ error={uninstallError ? 'uninstall' : 'install'}+ handleUninstall={handleUninstall}+ handleOpenInstallSheet={handleOpenInstallSheet}+ isUpgrade={upgradeAvailable}+ installing={installing}+ uninstalling={uninstalling}+ />+ ) : null+ }+ status={+ <StatusDisplay+ status={installationStatus}+ isInstallRequested={isInstallRequested}+ isInstallInitiated={isInstallInitiated}+ isUninstallRequested={isUninstallRequested}+ isUninstallInitiated={isUninstallInitiated}+ isUpgrade={upgradeAvailable}+ timedOut={timedOut}+ />+ }+ actions={+ !installed && !uninstalling && !uninstallError ? (+ <>+ <StripeSyncChangesCard+ installationStatus={installationStatus}+ isUpgrade={upgradeAvailable}+ />+ <IntegrationNotInstalledActions+ className="mt-4"+ installing={installing}+ canInstall={canInstall}+ isUninstallRequested={isUninstallRequested}+ handleUninstall={handleUninstall}+ setShouldShowInstallSheet={setShouldShowInstallSheet}+ />+ </>+ ) : installed || uninstalling || uninstallError ? (+ <>+ <StripeSyncChangesCard+ installationStatus={installationStatus}+ isUpgrade={upgradeAvailable}+ />+ <IntegrationInstalledActions+ className="mt-4"+ disabled={installing || uninstalling || !canManageSecrets}+ upgradeAvailable={upgradeAvailable}+ installing={installing}+ uninstalling={uninstalling}+ isUninstallRequested={isUninstallRequested}+ setShouldShowInstallSheet={setShouldShowInstallSheet}+ setShowUninstallModal={setShowUninstallModal}+ />+ </>+ ) : null+ }+ >+ <Sheet open={!!shouldShowInstallSheet} onOpenChange={handleCloseInstallSheet}>+ <SheetContent size="lg" tabIndex={undefined} className="flex flex-col gap-0">+ <Form_Shadcn_ {...form}>+ <form+ id={formId}+ onSubmit={form.handleSubmit(({ stripeSecretKey }) => {+ if (!project?.ref) return+ installStripeSync({+ projectRef: project.ref,+ stripeSecretKey,+ startTime: Date.now(),+ })+ })}+ className="overflow-auto flex-grow px-0 flex flex-col"+ >+ <SheetHeader>+ <SheetTitle>+ {upgradeAvailable ? 'Upgrade' : 'Install'} Stripe Sync Engine+ </SheetTitle>+ </SheetHeader>+ <SheetSection className="flex-1 flex flex-col gap-y-6">+ <StripeSyncChangesCard+ installationStatus={installationStatus}+ isUpgrade={upgradeAvailable}+ />++ <h3 className="heading-default">Configuration</h3>++ <div className="flex flex-col gap-y-2">+ <FormField_Shadcn_+ control={form.control}+ name="stripeSecretKey"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Stripe API secret key"+ description="Your Stripe secret key. Requires write access to Webhook Endpoints and read-only access to all other categories."+ >+ <FormControl_Shadcn_ className="col-span-8">+ <Input+ id="stripe_api_key"+ name="stripe_api_key"+ placeholder="Enter your Stripe API key"+ autoComplete="stripe-api-key"+ reveal={false}+ disabled={isInstallRequested}+ type="password"+ value={field.value}+ onChange={(e) => field.onChange(e.target.value)}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <div className="flex items-center gap-x-2">+ <Button asChild type="default" icon={<ExternalLink />}>+ <Link+ target="_blank"+ rel="noopener noreferrer"+ href="https://dashboard.stripe.com/apikeys"+ >+ Get Stripe API key+ </Link>+ </Button>+ <Button asChild type="default" icon={<ExternalLink />}>+ <Link+ target="_blank"+ rel="noopener noreferrer"+ href="https://support.stripe.com/questions/what-are-stripe-api-keys-and-how-to-find-them"+ >+ What are Stripe API keys?+ </Link>+ </Button>+ </div>+ </div>++ {installRequestError && (+ <Admonition+ type="destructive"+ title="Installation failed"+ description={installRequestError.message}+ />+ )}+ </SheetSection>++ <SheetFooter>+ <Button+ type="default"+ disabled={isInstallRequested}+ onClick={() => handleCloseInstallSheet(false)}+ >+ Cancel+ </Button>+ <Button+ form={formId}+ htmlType="submit"+ type="primary"+ loading={isInstallRequested}+ disabled={!form.formState.isValid || isInstallRequested}+ >+ {isInstallRequested+ ? upgradeAvailable+ ? 'Upgrading'+ : 'Installing'+ : upgradeAvailable+ ? 'Upgrade integration'+ : 'Install integration'}+ </Button>+ </SheetFooter>+ </form>+ </Form_Shadcn_>+ </SheetContent>+ </Sheet>+ </IntegrationOverviewTab>+ )}+ <ConfirmationModal+ visible={showUninstallModal}+ title="Uninstall Stripe Sync Engine"+ confirmLabel="Uninstall"+ confirmLabelLoading="Uninstalling..."+ variant="destructive"+ loading={isUninstallRequested}+ onCancel={() => setShowUninstallModal(false)}+ onConfirm={handleUninstall}+ >+ <p className="text-sm text-foreground-light">+ Are you sure you want to uninstall the Stripe Sync Engine? This will:+ </p>+ <ul className="list-disc pl-5 mt-2 text-sm text-foreground-light space-y-1">+ <li>+ Remove the <code className="text-code-inline">stripe</code> schema and all tables+ </li>+ <li>Delete all synced Stripe data</li>+ <li>Remove the associated Edge Functions</li>+ <li>Remove the scheduled sync jobs</li>+ </ul>+ <p className="mt-4 text-sm text-foreground-light font-medium">+ This action cannot be undone.+ </p>+ </ConfirmationModal>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/StripeSyncSettingsPage.tsx b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/StripeSyncSettingsPage.tsxindex 3167c5c4010..91db3cae5fb 100644--- a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/StripeSyncSettingsPage.tsx+++ b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/StripeSyncSettingsPage.tsx@@ -1,3 +1,4 @@+import { useParams } from 'common'import { formatRelative } from 'date-fns'import { BadgeCheck, RefreshCwIcon } from 'lucide-react'import Link from 'next/link'@@ -15,18 +16,14 @@ import {import { isInstalled, isSyncRunning, isUninstalling } from './stripe-sync-status'import { useStripeSyncStatus } from '@/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus'-import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'export const StripeSyncSettingsPage = () => {- const { data: project } = useSelectedProjectQuery()+ const { ref } = useParams()const {schemaComment: { status: installationStatus },syncState,- } = useStripeSyncStatus({- projectRef: project?.ref,- connectionString: project?.connectionString,- })+ } = useStripeSyncStatus()const installed = isInstalled(installationStatus)const isSyncing = isSyncRunning(syncState)const uninstalling = isUninstalling(installationStatus)@@ -117,9 +114,7 @@ export const StripeSyncSettingsPage = () => {</div><Button asChild type="default" className="ml-8 @md:ml-0">- <Link href={`/project/${project?.ref}/editor?schema=stripe`}>- Open Table Editor- </Link>+ <Link href={`/project/${ref}/editor?schema=stripe`}>Open Table Editor</Link></Button></div></CardContent>diff --git a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus.ts b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus.tsindex 31e13afdd14..641c510fb99 100644--- a/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus.ts+++ b/apps/studio/components/interfaces/Integrations/templates/StripeSyncEngine/useStripeSyncStatus.ts@@ -1,5 +1,5 @@+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { useEffect } from 'react'-import { checkDomainOfScale } from 'recharts/types/util/ChartUtils'import { getCurrentVersion, parseSchemaComment } from 'stripe-experiment-sync/supabase'import {@@ -9,31 +9,12 @@ import {type StripeSyncStatusResult,} from '@/components/interfaces/Integrations/templates/StripeSyncEngine/stripe-sync-status'import { useStripeSyncingState } from '@/data/database-integrations/stripe/sync-state-query'-import { SchemasVariables, useSchemasQuery } from '@/data/database/schemas-query'+import { Schema, useSchemasQuery } from '@/data/database/schemas-query'// Maximum time allowed for installation or uninstallation operations before the UI times outconst OPERATION_TIME_OUT_MS: number = 5 * 60 * 1000 // 5 minutes-/**- * Unified hook for Stripe Sync installation status.- *- * This hook consolidates all schema querying, status parsing, and polling logic- * into a single source of truth. It returns a discriminated union status that- * makes impossible states unrepresentable.- */-export function useStripeSyncStatus({- projectRef,- connectionString,-}: SchemasVariables): StripeSyncStatusResult {- const latestAvailableVersion = getCurrentVersion()-- // Query schemas once- const {- data: schemas,- isLoading: isSchemasLoading,- refetch,- } = useSchemasQuery({ projectRef, connectionString }, { enabled: !!projectRef })-+export const getStripeSyncSchemaComment = (schemas: Schema[]) => {// Find and parse stripe schema statusconst stripeSchema = findStripeSchema(schemas)const rawSchemaComment = parseSchemaComment(stripeSchema?.comment)@@ -59,8 +40,30 @@ export function useStripeSyncStatus({: rawSchemaComment.errorMessage: rawSchemaComment.errorMessage- const schemaComment = { ...rawSchemaComment, status, errorMessage }+ return { ...rawSchemaComment, status, errorMessage, timedOut }+}++/**+ * Unified hook for Stripe Sync installation status.+ *+ * This hook consolidates all schema querying, status parsing, and polling logic+ * into a single source of truth. It returns a discriminated union status that+ * makes impossible states unrepresentable.+ */+export function useStripeSyncStatus(): StripeSyncStatusResult {+ const latestAvailableVersion = getCurrentVersion()+ const { data: project } = useSelectedProjectQuery()+ const { ref: projectRef, connectionString } = project || {}++ // Query schemas once+ const {+ data: schemas,+ isLoading: isSchemasLoading,+ refetch,+ } = useSchemasQuery({ projectRef, connectionString }, { enabled: !!projectRef })+ const schemaComment = getStripeSyncSchemaComment(schemas ?? [])+ const timedOut = schemaComment.timedOutconst installed = isInstalled(schemaComment.status)const inProgress = isInProgress(schemaComment.status)diff --git a/apps/studio/pages/project/[ref]/integrations/[id]/[pageId]/index.tsx b/apps/studio/pages/project/[ref]/integrations/[id]/[pageId]/index.tsxindex 3fbfc121d79..1721ca2677b 100644--- a/apps/studio/pages/project/[ref]/integrations/[id]/[pageId]/index.tsx+++ b/apps/studio/pages/project/[ref]/integrations/[id]/[pageId]/index.tsx@@ -35,7 +35,7 @@ import {} from 'ui-patterns'import ShimmeringLoader, { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'-import { InstallIntegrationSheet } from '@/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet'+import { InstallIntegrationSheet } from '@/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/InstallIntegrationSheet/InstallIntegrationSheet'import { useAvailableIntegrations } from '@/components/interfaces/Integrations/Landing/useAvailableIntegrations'import { ProjectIntegrationsLayout } from '@/components/layouts/ProjectIntegrationsLayout'