The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): add support satisfaction survey page (#51648)
barcofouriec8c12a87b46a
diff --git a/apps/studio/TANSTACK_MIGRATION.md b/apps/studio/TANSTACK_MIGRATION.mdindex b07f589a098..76f013f044e 100644--- a/apps/studio/TANSTACK_MIGRATION.md+++ b/apps/studio/TANSTACK_MIGRATION.md@@ -366,6 +366,7 @@ These are the layout-only TanStack files. Most hold a single product layout comp- [x] A `routes/logout.tsx` ← `pages/logout.tsx`- [x] A `routes/maintenance.tsx` ← `pages/maintenance.tsx`- [x] A `routes/verify-email.tsx` ← `pages/verify-email.tsx`+- [x] A `routes/support/csat.tsx` ← `pages/support/csat.tsx` (pre-auth support satisfaction survey; page brings its own `InterstitialLayout`, so it stays outside `_app/`.)- [x] A `routes/mcp/secrets.tsx` ← `pages/mcp/secrets.tsx` (MCP elicitation URL-mode handoff; page brings its own `InterstitialLayout`, so it stays outside `_app/`.)### Error pages (handled at root)diff --git a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.ts b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.tsnew file mode 100644index 00000000000..4a963cc614c--- /dev/null+++ b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest'++import { csatSurveyParamsSchema } from './CsatSurvey.schema'++describe('parseCsatSurveyParams', () => {+ it('returns a valid result with the yes answer preselected', () => {+ expect(+ csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful: 'yes' })+ ).toEqual({+ success: true,+ data: {+ conversation_id: 'cnv_1abc2',+ helpful: true,+ },+ })+ })++ it('returns a valid result with the no answer preselected', () => {+ expect(+ csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful: 'no' })+ ).toEqual({+ success: true,+ data: {+ conversation_id: 'cnv_1abc2',+ helpful: false,+ },+ })+ })++ it('preselects yes when helpful is missing or unknown', () => {+ expect(csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2' })).toEqual({+ success: true,+ data: {+ conversation_id: 'cnv_1abc2',+ helpful: true,+ },+ })+ expect(+ csatSurveyParamsSchema.safeParse({ conversation_id: 'cnv_1abc2', helpful: 'maybe' })+ ).toEqual({+ success: true,+ data: {+ conversation_id: 'cnv_1abc2',+ helpful: true,+ },+ })+ })++ it('trims whitespace around the conversation id', () => {+ expect(csatSurveyParamsSchema.safeParse({ conversation_id: ' cnv_1abc2 ' })).toEqual({+ success: true,+ data: {+ conversation_id: 'cnv_1abc2',+ helpful: true,+ },+ })+ })++ it.each([undefined, '', 'cnv_', 'CNV_1ABC', '1abc2', 'cnv_1abc2/extra', 'cnv_1abc2;drop'])(+ 'rejects the conversation id %s',+ (conversation_id) => {+ expect(csatSurveyParamsSchema.safeParse({ conversation_id, helpful: 'yes' })).toMatchObject({+ success: false,+ })+ }+ )+})diff --git a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.ts b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.tsnew file mode 100644index 00000000000..4d0757201d5--- /dev/null+++ b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.schema.ts@@ -0,0 +1,25 @@+import { z } from 'zod'++export const CSAT_COMMENT_MAX_LENGTH = 2000++export const CsatSurveyFormSchema = z.object({+ satisfied: z.boolean(),+ comment: z.string().trim().max(CSAT_COMMENT_MAX_LENGTH, 'Comment is too long'),+})++export type CsatSurveyFormValues = z.infer<typeof CsatSurveyFormSchema>++const CONVERSATION_ID_PATTERN = /^cnv_[a-z0-9]+$/++// The survey email links to ?helpful=yes and ?helpful=no; anything else preselects Yes, as the original page did.+function parseHelpful(helpful: string | undefined): boolean {+ return helpful !== 'no'+}++export const csatSurveyParamsSchema = z.object({+ conversation_id: z.preprocess(+ (value) => String(value)?.trim(),+ z.string().regex(CONVERSATION_ID_PATTERN)+ ),+ helpful: z.string().optional().transform(parseHelpful),+})diff --git a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsx b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsxnew file mode 100644index 00000000000..3b8c77836ac--- /dev/null+++ b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.test.tsx@@ -0,0 +1,123 @@+import { fireEvent, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { http, HttpResponse, type JsonBodyType } from 'msw'+import { beforeEach, describe, expect, test, vi } from 'vitest'++import { CsatSurvey } from './CsatSurvey'+import { API_URL } from '@/lib/constants'+import { customRender } from '@/tests/lib/custom-render'+import { mswServer } from '@/tests/lib/msw'+import { routerMock } from '@/tests/lib/route-mock'++// The global test setup stubs useParams; restore the real one so the URL query drives the page.+vi.mock('common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('common')>()+ return { ...actual, useParams: actual.useParams }+})++const CSAT_URL = `${API_URL?.replace('/platform', '')}/platform/support/csat`++const mockSubmit = (status: number, body: JsonBodyType = { result: 'success' }) => {+ const requests: unknown[] = []+ mswServer.use(+ http.post(CSAT_URL, async ({ request }) => {+ requests.push(await request.json())+ return HttpResponse.json(body, { status })+ })+ )+ return requests+}++// Click-to-submit does not work under the test pointer-event polyfill; submit the form directly.+const submitForm = () => {+ const form = screen.getByRole('button', { name: 'Submit' }).closest('form')+ if (!form) throw new Error('Survey form not found')+ fireEvent.submit(form)+}++describe('CsatSurvey', () => {+ beforeEach(() => {+ routerMock.setCurrentUrl('/support/csat?conversation_id=cnv_1abc2&helpful=yes')+ })++ test('shows the ticket error when the link has no ticket reference', () => {+ routerMock.setCurrentUrl('/support/csat')++ customRender(<CsatSurvey />)++ expect(screen.getByText('Invalid or mismatched ticket')).toBeInTheDocument()+ })++ test('preselects the answer from the link and submits it with a comment', async () => {+ const requests = mockSubmit(200)++ customRender(<CsatSurvey />)++ expect(screen.getByRole('button', { name: 'Yes' })).toHaveAttribute('aria-pressed', 'true')+ await userEvent.type(screen.getByLabelText(/add a comment/i), 'Quick and helpful')+ submitForm()++ expect(+ await screen.findByText('Survey response recorded. You can now close this window.')+ ).toBeInTheDocument()+ expect(requests).toEqual([+ { conversation_id: 'cnv_1abc2', satisfied: true, comment: 'Quick and helpful' },+ ])+ })++ test('lets the customer change the answer before submitting', async () => {+ const requests = mockSubmit(200)++ customRender(<CsatSurvey />)++ await userEvent.click(screen.getByRole('button', { name: 'No' }))+ submitForm()++ await waitFor(() => expect(requests).toHaveLength(1))+ expect(requests[0]).toMatchObject({ conversation_id: 'cnv_1abc2', satisfied: false })+ })++ test('defaults to yes when the link did not preselect an answer', async () => {+ routerMock.setCurrentUrl('/support/csat?conversation_id=cnv_1abc2')+ const requests = mockSubmit(200)++ customRender(<CsatSurvey />)++ expect(screen.getByRole('button', { name: 'Yes' })).toHaveAttribute('aria-pressed', 'true')+ submitForm()++ await waitFor(() => expect(requests).toHaveLength(1))+ expect(requests[0]).toMatchObject({ conversation_id: 'cnv_1abc2', satisfied: true })+ })++ test('shows the already-submitted error on a 409', async () => {+ mockSubmit(409, { message: 'This survey has already been answered' })++ customRender(<CsatSurvey />)++ submitForm()++ expect(await screen.findByText('This survey has already been submitted')).toBeInTheDocument()+ })++ test('shows the ticket error on a 404', async () => {+ mockSubmit(404, { message: 'No survey was sent for this conversation' })++ customRender(<CsatSurvey />)++ submitForm()++ expect(await screen.findByText('Invalid or mismatched ticket')).toBeInTheDocument()+ })++ test('keeps the form and shows the error on other failures', async () => {+ mockSubmit(500, { message: 'Failed to record survey response' })++ customRender(<CsatSurvey />)++ submitForm()++ expect(await screen.findByText('Failed to record survey response')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument()+ })+})diff --git a/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.tsx b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.tsxnew file mode 100644index 00000000000..48f49fcb2a9--- /dev/null+++ b/apps/studio/components/interfaces/Support/CsatSurvey/CsatSurvey.tsx@@ -0,0 +1,159 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { useParams } from 'common'+import type { ReactNode } from 'react'+import { useForm, useWatch } from 'react-hook-form'+import { Button, Form, FormControl, FormField, TextArea } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import {+ CSAT_COMMENT_MAX_LENGTH,+ CsatSurveyFormSchema,+ csatSurveyParamsSchema,+ type CsatSurveyFormValues,+} from './CsatSurvey.schema'+import { InterstitialLayout, SupabaseLogo } from '@/components/layouts/InterstitialLayout'+import { useCsatSurveyMutation } from '@/data/support/csat-survey-mutation'++const PAGE_TITLE = 'Customer Satisfaction Survey'++const withLayout = (children: ReactNode) => (+ <InterstitialLayout logo={<SupabaseLogo />} title={PAGE_TITLE}>+ <div className="px-6 pb-6">{children}</div>+ </InterstitialLayout>+)++export const CsatSurvey = () => {+ const { conversation_id, helpful } = useParams()+ const paramsParsingResult = csatSurveyParamsSchema.safeParse({ conversation_id, helpful })++ if (!paramsParsingResult.success) {+ return withLayout(+ <Admonition type="destructive" title="Error" description="Invalid or mismatched ticket" />+ )+ }++ return (+ <CsatSurveyForm+ conversationId={paramsParsingResult.data.conversation_id}+ initialSatisfied={paramsParsingResult.data.helpful}+ />+ )+}++const CsatSurveyForm = ({+ conversationId,+ initialSatisfied,+}: {+ conversationId: string+ initialSatisfied: boolean+}) => {+ const {+ mutate: submitSurvey,+ isPending,+ isSuccess,+ isError,+ error,+ } = useCsatSurveyMutation({ onError: () => {} })++ const form = useForm<CsatSurveyFormValues>({+ resolver: zodResolver(CsatSurveyFormSchema),+ defaultValues: { satisfied: initialSatisfied, comment: '' },+ })+ const satisfied = useWatch({ control: form.control, name: 'satisfied' })++ const onSubmit = (values: CsatSurveyFormValues) => {+ submitSurvey({+ conversationId,+ satisfied: values.satisfied,+ comment: values.comment || undefined,+ })+ }++ if (isSuccess) {+ return withLayout(+ <Admonition+ type="success"+ title="Success"+ description="Survey response recorded. You can now close this window."+ />+ )+ }++ const isAlreadySubmitted = isError && error.code === 409+ if (isAlreadySubmitted) {+ return withLayout(+ <Admonition+ type="destructive"+ title="Error"+ description="This survey has already been submitted"+ />+ )+ }++ const isTicketMismatch = isError && error.code === 404+ if (isTicketMismatch) {+ return withLayout(+ <Admonition type="destructive" title="Error" description="Invalid or mismatched ticket" />+ )+ }++ return withLayout(+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">+ <FormField+ control={form.control}+ name="satisfied"+ render={({ field }) => (+ <FormItemLayout+ layout="vertical"+ label="Were you satisfied with your Supabase Support Experience?"+ >+ <FormControl>+ <div+ className="flex gap-2"+ role="group"+ aria-label="Were you satisfied with your Supabase Support Experience?"+ >+ <Button+ type="button"+ variant={satisfied === true ? 'primary' : 'default'}+ aria-pressed={satisfied === true}+ onClick={() => field.onChange(true)}+ block+ >+ Yes+ </Button>+ <Button+ type="button"+ variant={satisfied === false ? 'primary' : 'default'}+ aria-pressed={satisfied === false}+ onClick={() => field.onChange(false)}+ block+ >+ No+ </Button>+ </div>+ </FormControl>+ </FormItemLayout>+ )}+ />+ <FormField+ control={form.control}+ name="comment"+ render={({ field }) => (+ <FormItemLayout layout="vertical" label="Would you like to add a comment?">+ <FormControl>+ <TextArea {...field} rows={4} maxLength={CSAT_COMMENT_MAX_LENGTH} />+ </FormControl>+ </FormItemLayout>+ )}+ />+ {isError && <Admonition type="destructive" title="Error" description={error.message} />}+ <Button type="submit" variant="primary" loading={isPending} block>+ Submit+ </Button>+ </form>+ </Form>+ )+}diff --git a/apps/studio/data/support/csat-survey-mutation.ts b/apps/studio/data/support/csat-survey-mutation.tsnew file mode 100644index 00000000000..9b4beea39e5--- /dev/null+++ b/apps/studio/data/support/csat-survey-mutation.ts@@ -0,0 +1,63 @@+import { useMutation } from '@tanstack/react-query'+import { toast } from 'sonner'++import { constructHeaders, fetchHandler, handleError } from '@/data/fetchers'+import { API_URL } from '@/lib/constants'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type CsatSurveyVariables = {+ conversationId: string+ satisfied: boolean+ comment?: string+}++export type CsatSurveyData = {+ result: 'success'+}++export async function submitCsatSurvey({+ conversationId,+ satisfied,+ comment,+}: CsatSurveyVariables): Promise<CsatSurveyData> {+ const baseUrl = API_URL?.replace('/platform', '')+ const url = `${baseUrl}/platform/support/csat`+ const headers = await constructHeaders({ 'Content-Type': 'application/json' })++ const res = await fetchHandler(url, {+ method: 'POST',+ headers,+ body: JSON.stringify({ conversation_id: conversationId, satisfied, comment }),+ })++ if (!res.ok) {+ const body = await res.json().catch(() => ({}))+ handleError({ ...body, code: res.status })+ }++ return res.json() as Promise<CsatSurveyData>+}++export const useCsatSurveyMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<CsatSurveyData, ResponseError, CsatSurveyVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<CsatSurveyData, ResponseError, CsatSurveyVariables>({+ mutationFn: (vars) => submitCsatSurvey(vars),+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to submit survey: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/pages/support/csat.tsx b/apps/studio/pages/support/csat.tsxnew file mode 100644index 00000000000..b8cd79dd3b9--- /dev/null+++ b/apps/studio/pages/support/csat.tsx@@ -0,0 +1,42 @@+import Head from 'next/head'+import { useRouter } from 'next/router'+import { useEffect } from 'react'++import { CsatSurvey } from '@/components/interfaces/Support/CsatSurvey/CsatSurvey'+import { IS_PLATFORM } from '@/lib/constants'+import { buildStudioPageTitle } from '@/lib/page-title'+import type { NextPageWithLayout } from '@/types'++const PAGE_TITLE = buildStudioPageTitle({+ section: 'Customer Satisfaction Survey',+ brand: 'Supabase',+})++/**+ * Pre-auth page: customers land here from the satisfaction survey link in a resolved+ * support ticket email, so there may be no dashboard session. Hosted platform only.+ */+const CsatSurveyPage: NextPageWithLayout = () => {+ const router = useRouter()++ useEffect(() => {+ if (!IS_PLATFORM) {+ router.replace('/404')+ }+ }, [router])++ if (!IS_PLATFORM) {+ return null+ }++ return (+ <>+ <Head>+ <title>{PAGE_TITLE}</title>+ </Head>+ <CsatSurvey />+ </>+ )+}++export default CsatSurveyPagediff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.tsindex 084b014185d..b2f86cc10b1 100644--- a/apps/studio/routeTree.gen.ts+++ b/apps/studio/routeTree.gen.ts@@ -53,6 +53,7 @@ import { Route as NewSlugRouteImport } from './routes/new/$slug'import { Route as OrgChar91_Char93RouteImport } from './routes/org.[_]'import { Route as ProjectRefRouteImport } from './routes/project/$ref'import { Route as ProjectChar91_Char93RouteImport } from './routes/project.[_]'+import { Route as SupportCsatRouteImport } from './routes/support/csat'import { Route as AppAccountAppsRouteImport } from './routes/_app/account/apps'import { Route as AppAccountAuditRouteImport } from './routes/_app/account/audit'import { Route as AppAccountMeRouteImport } from './routes/_app/account/me'@@ -557,6 +558,11 @@ const ProjectChar91_Char93Route = ProjectChar91_Char93RouteImport.update({path: '/project/_',getParentRoute: () => rootRouteImport,} as any)+const SupportCsatRoute = SupportCsatRouteImport.update({+ id: '/support/csat',+ path: '/support/csat',+ getParentRoute: () => rootRouteImport,+} as any)const AppAccountAppsRoute = AppAccountAppsRouteImport.update({id: '/apps',path: '/apps',@@ -2194,6 +2200,7 @@ export interface FileRoutesByFullPath {'/org/_': typeof OrgChar91_Char93RouteWithChildren'/project/$ref': typeof ProjectRefRouteWithChildren'/project/_': typeof ProjectChar91_Char93RouteWithChildren+ '/support/csat': typeof SupportCsatRoute'/account/apps': typeof AppAccountAppsRoute'/account/audit': typeof AppAccountAuditRoute'/account/me': typeof AppAccountMeRoute@@ -2517,6 +2524,7 @@ export interface FileRoutesByTo {'/new/$slug': typeof NewSlugRoute'/org/_': typeof OrgChar91_Char93RouteWithChildren'/project/_': typeof ProjectChar91_Char93RouteWithChildren+ '/support/csat': typeof SupportCsatRoute'/account/apps': typeof AppAccountAppsRoute'/account/audit': typeof AppAccountAuditRoute'/account/me': typeof AppAccountMeRoute@@ -2832,6 +2840,7 @@ export interface FileRoutesById {'/org/_': typeof OrgChar91_Char93RouteWithChildren'/project/$ref': typeof ProjectRefRouteWithChildren'/project/_': typeof ProjectChar91_Char93RouteWithChildren+ '/support/csat': typeof SupportCsatRoute'/_app/account/apps': typeof AppAccountAppsRoute'/_app/account/audit': typeof AppAccountAuditRoute'/_app/account/me': typeof AppAccountMeRoute@@ -3159,6 +3168,7 @@ export interface FileRouteTypes {| '/org/_'| '/project/$ref'| '/project/_'+ | '/support/csat'| '/account/apps'| '/account/audit'| '/account/me'@@ -3482,6 +3492,7 @@ export interface FileRouteTypes {| '/new/$slug'| '/org/_'| '/project/_'+ | '/support/csat'| '/account/apps'| '/account/audit'| '/account/me'@@ -3796,6 +3807,7 @@ export interface FileRouteTypes {| '/org/_'| '/project/$ref'| '/project/_'+ | '/support/csat'| '/_app/account/apps'| '/_app/account/audit'| '/_app/account/me'@@ -4112,6 +4124,7 @@ export interface RootRouteChildren {OrgChar91_Char93Route: typeof OrgChar91_Char93RouteWithChildrenProjectRefRoute: typeof ProjectRefRouteWithChildrenProjectChar91_Char93Route: typeof ProjectChar91_Char93RouteWithChildren+ SupportCsatRoute: typeof SupportCsatRouteApiAiDocsRoute: typeof ApiAiDocsRouteApiContentGraphqlRoute: typeof ApiContentGraphqlRouteApiEdgeFunctionsTestRoute: typeof ApiEdgeFunctionsTestRoute@@ -4516,6 +4529,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectChar91_Char93RouteImportparentRoute: typeof rootRouteImport}+ '/support/csat': {+ id: '/support/csat'+ path: '/support/csat'+ fullPath: '/support/csat'+ preLoaderRoute: typeof SupportCsatRouteImport+ parentRoute: typeof rootRouteImport+ }'/_app/account/apps': {id: '/_app/account/apps'path: '/apps'@@ -7255,6 +7275,7 @@ const rootRouteChildren: RootRouteChildren = {OrgChar91_Char93Route: OrgChar91_Char93RouteWithChildren,ProjectRefRoute: ProjectRefRouteWithChildren,ProjectChar91_Char93Route: ProjectChar91_Char93RouteWithChildren,+ SupportCsatRoute: SupportCsatRoute,ApiAiDocsRoute: ApiAiDocsRoute,ApiContentGraphqlRoute: ApiContentGraphqlRoute,ApiEdgeFunctionsTestRoute: ApiEdgeFunctionsTestRoute,diff --git a/apps/studio/routes/support/csat.tsx b/apps/studio/routes/support/csat.tsxnew file mode 100644index 00000000000..83096bd6446--- /dev/null+++ b/apps/studio/routes/support/csat.tsx@@ -0,0 +1,11 @@+import { createFileRoute } from '@tanstack/react-router'++import CsatSurveyPage from '@/pages/support/csat'++export const Route = createFileRoute('/support/csat')({+ component: CsatSurveyRoute,+})++function CsatSurveyRoute() {+ return <CsatSurveyPage dehydratedState={undefined} />+}