The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feat: CRUD custom reports (#21116)
Jordi Enric5ca65b4bcd62
diff --git a/apps/studio/components/interfaces/Reports/GridResize.tsx b/apps/studio/components/interfaces/Reports/GridResize.tsxindex 1d98e938f90..6e17cd4e33a 100644--- a/apps/studio/components/interfaces/Reports/GridResize.tsx+++ b/apps/studio/components/interfaces/Reports/GridResize.tsx@@ -1,5 +1,4 @@import RGL, { WidthProvider } from 'react-grid-layout'-import { LAYOUT_COLUMN_COUNT } from './Reports.constants'import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'diff --git a/apps/studio/components/interfaces/Reports/Reports.CreateReportModal.tsx b/apps/studio/components/interfaces/Reports/Reports.CreateReportModal.tsxnew file mode 100644index 00000000000..8040f37309f--- /dev/null+++ b/apps/studio/components/interfaces/Reports/Reports.CreateReportModal.tsx@@ -0,0 +1,112 @@+import { useContentInsertMutation } from 'data/content/content-insert-mutation'+import { useSelectedProject } from 'hooks'+import { uuidv4 } from 'lib/helpers'+import { useRouter } from 'next/router'+import toast from 'react-hot-toast'+import { Button, Form, Input, Modal } from 'ui'++type CustomReport = { name: string; description?: string }+export interface CreateReportModal {+ visible: boolean+ onCancel: () => void+ afterSubmit: () => void+}++export const CreateReportModal = ({ visible, onCancel, afterSubmit }: CreateReportModal) => {+ const project = useSelectedProject()+ const insertReport = useContentInsertMutation()+ const ref = project?.ref ?? 'default'+ const router = useRouter()++ async function createCustomReport({ name, description }: { name: string; description?: string }) {+ try {+ if (!ref) return++ const res = await insertReport.mutateAsync({+ projectRef: ref,+ payload: {+ id: uuidv4(),+ type: 'report',+ name,+ description: description || '',+ visibility: 'project',+ content: {+ schema_version: 1,+ period_start: {+ time_period: '7d',+ date: '',+ },+ period_end: {+ time_period: 'today',+ date: '',+ },+ interval: '1d',+ layout: [],+ },+ },+ })+ toast.success('New report created')++ const newReportId = res[0].id+ router.push(`/project/${ref}/reports/${newReportId}`)+ afterSubmit()+ } catch (error) {+ toast.error(`Failed to create report. Check console for more details.`)+ console.error(error)+ }+ }++ return (+ <Modal+ visible={visible}+ onCancel={onCancel}+ hideFooter+ header="Create a custom report"+ size="small"+ >+ <Form+ onReset={onCancel}+ validateOnBlur+ initialValues={{ name: '', description: '' }}+ validate={(vals) => {+ const errors: Partial<CustomReport> = {}++ if (!vals.name) {+ errors.name = 'Required'+ }++ return errors+ }}+ onSubmit={(newVals) => createCustomReport(newVals)}+ >+ {({ isSubmitting }: { isSubmitting: boolean }) => (+ <div className="space-y-4 py-4">+ <Modal.Content>+ <Input label="Name" id="name" name="name" />+ </Modal.Content>+ <Modal.Content>+ <Input.TextArea+ label="Description"+ id="description"+ placeholder="Describe your custom report"+ size="medium"+ textAreaClassName="resize-none"+ />+ </Modal.Content>+ <Modal.Separator />+ <Modal.Content>+ <div className="flex items-center justify-end gap-2">+ <Button htmlType="reset" type="default" onClick={onCancel} disabled={isSubmitting}>+ Cancel+ </Button>+ <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting}>+ Create report+ </Button>+ </div>+ </Modal.Content>+ </div>+ )}+ </Form>+ </Modal>+ )+}diff --git a/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsx b/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsxnew file mode 100644index 00000000000..d305f58e114--- /dev/null+++ b/apps/studio/components/interfaces/Reports/Reports.UpdateModal.tsx@@ -0,0 +1,73 @@+import { Button, Form, Input, Modal } from 'ui'++type CustomReport = { name: string; description?: string }++export interface UpdateCustomReportProps {+ visible: boolean+ onCancel: () => void+ onSubmit: (newValues: CustomReport) => void+ initialValues: CustomReport+}++export const UpdateCustomReportModal = ({+ visible,+ onCancel,+ onSubmit,+ initialValues,+}: UpdateCustomReportProps) => {+ function validate(values: CustomReport) {+ const errors: Partial<CustomReport> = {}++ if (!values.name) {+ errors.name = 'Required'+ }++ return errors+ }++ return (+ <Modal+ visible={visible}+ onCancel={onCancel}+ hideFooter+ header="Update custom report"+ size="small"+ >+ <Form+ onReset={onCancel}+ validateOnBlur+ initialValues={initialValues}+ validate={validate}+ onSubmit={onSubmit}+ >+ {({ isSubmitting }: { isSubmitting: boolean }) => (+ <div className="space-y-4 py-4">+ <Modal.Content>+ <Input label="Name" id="name" name="name" />+ </Modal.Content>+ <Modal.Content>+ <Input.TextArea+ label="Description"+ id="description"+ placeholder="Describe your custom report"+ size="medium"+ textAreaClassName="resize-none"+ />+ </Modal.Content>+ <Modal.Separator />+ <Modal.Content>+ <div className="flex items-center justify-end gap-2">+ <Button htmlType="reset" type="default" onClick={onCancel} disabled={isSubmitting}>+ Cancel+ </Button>+ <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting}>+ Save custom report+ </Button>+ </div>+ </Modal.Content>+ </div>+ )}+ </Form>+ </Modal>+ )+}diff --git a/apps/studio/components/interfaces/Reports/Reports.queries.ts b/apps/studio/components/interfaces/Reports/Reports.queries.tsindex 6c76223b286..11e6cdded25 100644--- a/apps/studio/components/interfaces/Reports/Reports.queries.ts+++ b/apps/studio/components/interfaces/Reports/Reports.queries.ts@@ -1,6 +1,8 @@+import { useProjectContentStore } from 'stores/projectContentStore'import { PRESET_CONFIG } from './Reports.constants'import { Presets } from './Reports.types'import useDbQuery from 'hooks/analytics/useDbQuery'+import { useMutation, useQuery } from '@tanstack/react-query'type QueryPerformanceQueryOpts = {searchQuery: string@@ -27,7 +29,5 @@ export const useQueryPerformanceQuery = ({const sql = baseSQL.sql([], whereSql, orderBySql)- // console.log('DEBUG Using sql query: ', sql)-return useDbQuery(sql, undefined, whereSql, orderBySql)}diff --git a/apps/studio/components/interfaces/Reports/Reports.tsx b/apps/studio/components/interfaces/Reports/Reports.tsxindex b699757d6c7..e9b04020e8a 100644--- a/apps/studio/components/interfaces/Reports/Reports.tsx+++ b/apps/studio/components/interfaces/Reports/Reports.tsx@@ -33,6 +33,7 @@ import { useProfile } from 'lib/profile'import { useProjectContentStore } from 'stores/projectContentStore'import GridResize from './GridResize'import { LAYOUT_COLUMN_COUNT } from './Reports.constants'+import { useContentQuery } from 'data/content/content-query'const DEFAULT_CHART_COLUMN_COUNT = 12const DEFAULT_CHART_ROW_COUNT = 4@@ -46,6 +47,10 @@ const Reports = () => {'project_storage:all',])+ const reportQuery = useContentQuery(ref)+ const currentReport =+ reportQuery.data && reportQuery.data?.content.find((report) => report.id === id)+const [report, setReport] = useState<any>()const [loading, setLoading] = useState<any>(false)@@ -314,9 +319,11 @@ const Reports = () => {}return (- <div className="mx-6 flex flex-col space-y-4" style={{ maxHeight: '100%' }}>- <h1 className="text-xl text-foreground">Reports</h1>-+ <div className="flex flex-col space-y-4" style={{ maxHeight: '100%' }}>+ <div className="space-y-0.5">+ <h1 className="text-xl text-foreground">{currentReport?.name || 'Reports'}</h1>+ <p className="text-foreground-light">{currentReport?.description}</p>+ </div><div className="mb-4 flex items-center justify-between space-x-3"><div className="flex items-center space-x-3"><DateRangePicker@@ -419,7 +426,6 @@ const Reports = () => {) : (<div className="relative mb-16 max-w-7xl flex-grow">{config && startDate && endDate && (- // @ts-ignore<GridResizestartDate={startDate}endDate={endDate}diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsLayout.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsLayout.tsxindex 3ec45efeff2..d0d9168bbce 100644--- a/apps/studio/components/layouts/ReportsLayout/ReportsLayout.tsx+++ b/apps/studio/components/layouts/ReportsLayout/ReportsLayout.tsx@@ -1,78 +1,15 @@-import { useRouter } from 'next/router'import { PropsWithChildren } from 'react'--import ProductMenu from 'components/ui/ProductMenu'-import { useIsFeatureEnabled, useSelectedProject, withAuth } from 'hooks'+import { withAuth } from 'hooks'import ProjectLayout from '../'+import ReportsMenu from './ReportsMenu'interface ReportsLayoutProps {title?: string}const ReportsLayout = ({ title, children }: PropsWithChildren<ReportsLayoutProps>) => {- const router = useRouter()-- const project = useSelectedProject()- const page = router.pathname.split('/')[4] || ''- const ref = project?.ref ?? 'default'-- const storageEnabled = useIsFeatureEnabled('project_storage:all')-- const menuItems = [- {- key: 'reports',- items: [- {- name: 'Custom reports',- key: '[id]',- url: `/project/${ref}/reports`,- items: [],- },- ],- },- {- key: 'builtin-reports',- items: [- {- name: 'API',- key: 'api-overview',- url: `/project/${ref}/reports/api-overview`,- items: [],- },- ...(storageEnabled- ? [- {- name: 'Storage',- key: 'storage',- url: `/project/${ref}/reports/storage`,- items: [],- label: 'NEW',- },- ]- : []),-- {- name: 'Database',- key: 'database',- url: `/project/${ref}/reports/database`,- items: [],- },- {- name: 'Query Performance',- key: 'query-performance',- url: `/project/${ref}/reports/query-performance`,- items: [],- },- ],- },- ]-return (- <ProjectLayout- title={title}- product="Reports"- productMenu={<ProductMenu page={page} menu={menuItems} />}- >+ <ProjectLayout title={title} product="Reports" productMenu={<ReportsMenu />}><main style={{ maxHeight: '100vh' }} className="flex-1 overflow-y-auto">{children}</main>diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsxnew file mode 100644index 00000000000..07201122f3e--- /dev/null+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx@@ -0,0 +1,331 @@+import { CreateReportModal } from 'components/interfaces/Reports/Reports.CreateReportModal'+import { UpdateCustomReportModal } from 'components/interfaces/Reports/Reports.UpdateModal'+import ConfirmationModal from 'components/ui/ConfirmationModal'+import ShimmeringLoader from 'components/ui/ShimmeringLoader'+import { useContentDeleteMutation } from 'data/content/content-delete-mutation'+import { useContentInsertMutation } from 'data/content/content-insert-mutation'+import { Content, useContentQuery } from 'data/content/content-query'+import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'+import { useIsFeatureEnabled, useSelectedProject } from 'hooks'+import { uuidv4 } from 'lib/helpers'+import Link from 'next/link'+import { useRouter } from 'next/router'+import React from 'react'+import toast from 'react-hot-toast'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ IconChevronDown,+ IconEdit2,+ IconPlus,+ IconTrash,+ Menu,+ Modal,+ cn,+} from 'ui'++const ReportsMenu = () => {+ const router = useRouter()+ const insertReport = useContentInsertMutation()+ const deleteReport = useContentDeleteMutation()+ const updateReport = useContentUpsertMutation()++ const project = useSelectedProject()+ const { id } = router.query+ const pageKey = (id || router.pathname.split('/')[4]) as string+ const ref = project?.ref ?? 'default'++ const [deleteModalOpen, setDeleteModalOpen] = React.useState(false)+ const [showNewReportModal, setShowNewReportModal] = React.useState(false)+ const [showUpdateReportModal, setShowUpdateReportModal] = React.useState(false)+ const [selectedReport, setSelectedReport] = React.useState<Content>()++ const storageEnabled = useIsFeatureEnabled('project_storage:all')++ const { data: content, isLoading } = useContentQuery(ref)++ function getReportMenuItems() {+ if (!content) return []++ const reports = content?.content.filter((c) => c.type === 'report')++ const sortedReports = reports?.sort((a, b) => {+ if (a.name < b.name) {+ return -1+ }+ if (a.name > b.name) {+ return 1+ }+ return 0+ })++ const reportMenuItems = sortedReports.map((r, idx) => ({+ id: r.id,+ name: r.name,+ description: r.description || '',+ key: r.id || idx + '-report',+ url: `/project/${ref}/reports/${r.id}`,+ hasDropdownActions: true,+ report: r,+ }))++ return reportMenuItems+ }++ const reportMenuItems = getReportMenuItems()++ const menuItems = [+ {+ title: 'Built-in reports',+ key: 'builtin-reports',+ items: [+ {+ name: 'API',+ key: 'api-overview',+ url: `/project/${ref}/reports/api-overview`,+ },+ ...(storageEnabled+ ? [+ {+ name: 'Storage',+ key: 'storage',+ url: `/project/${ref}/reports/storage`,+ },+ ]+ : []),++ {+ name: 'Database',+ key: 'database',+ url: `/project/${ref}/reports/database`,+ },+ {+ name: 'Query Performance',+ key: 'query-performance',+ url: `/project/${ref}/reports/query-performance`,+ },+ ],+ },+ ]++ async function createCustomReport({ name, description }: { name: string; description?: string }) {+ try {+ if (!ref) return++ const res = await insertReport.mutateAsync({+ projectRef: ref,+ payload: {+ id: uuidv4(),+ type: 'report',+ name,+ description: description || '',+ visibility: 'project',+ content: {+ schema_version: 1,+ period_start: {+ time_period: '7d',+ date: '',+ },+ period_end: {+ time_period: 'today',+ date: '',+ },+ interval: '1d',+ layout: [],+ },+ },+ })+ toast.success('New report created')++ const newReportId = res[0].id+ setShowNewReportModal(false)+ router.push(`/project/${ref}/reports/${newReportId}`)+ } catch (error) {+ toast.error(`Failed to create report. Check console for more details.`)+ console.error(error)+ }+ }++ return (+ <Menu type="pills" className="mt-6">+ {isLoading ? (+ <div className="px-5 my-4 space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ ) : (+ <div className="flex flex-col px-2">+ <div className="flex px-2">+ <Button+ type="default"+ className="justify-start flex-grow"+ onClick={() => {+ setShowNewReportModal(true)+ }}+ icon={<IconPlus size="tiny" />}+ >+ New custom report+ </Button>+ </div>+ {reportMenuItems.length > 0 ? (+ <div className="mt-6">+ <Menu.Group title={'Your custom reports'} />+ {reportMenuItems.map((item, idx) => (+ <Link+ className={cn(+ 'pr-2 h-7 pl-3 mt-1 text-foreground-light group-hover:text-foreground/80 text-sm',+ 'flex items-center justify-between rounded-md group relative',+ item.key === pageKey ? 'bg-surface-300 text-foreground' : 'hover:bg-surface-200'+ )}+ key={item.key + '-menukey'}+ href={item.url}+ >+ <div>{item.name}</div>++ <DropdownMenu>+ <DropdownMenuTrigger>+ <Button+ type="text"+ className="px-1 opacity-50 hover:opacity-100"+ icon={<IconChevronDown size="tiny" strokeWidth={2} />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-52 *:space-x-2">+ <DropdownMenuItem+ onClick={() => {+ if (!item.id) return+ setSelectedReport(item.report)+ setShowUpdateReportModal(true)+ }}+ >+ <IconEdit2 size="tiny" />+ <div>Rename</div>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={async () => {+ if (!item.id) return+ setSelectedReport(item.report)+ setDeleteModalOpen(true)+ }}+ >+ <IconTrash size="tiny" />+ <div>Delete</div>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </Link>+ ))}+ </div>+ ) : null}+ {menuItems.map((item, idx) => (+ <div className="mt-6" key={item.key + '-menu-group'}>+ {item.items ? (+ <>+ <Menu.Group title={item.title} />+ <div key={item.key} className="flex flex-col">+ {item.items.map((subItem) => (+ <li+ key={subItem.key}+ className={cn(+ 'pr-2 mt-1 text-foreground-light group-hover:text-foreground/80 text-sm',+ 'flex items-center justify-between rounded-md group relative',+ subItem.key === pageKey+ ? 'bg-surface-300 text-foreground'+ : 'hover:bg-surface-200'+ )}+ >+ <Link href={subItem.url} className="flex-grow h-7 flex items-center pl-3">+ {subItem.name}+ </Link>+ </li>+ ))}+ </div>+ </>+ ) : null}+ </div>+ ))}+ <UpdateCustomReportModal+ onSubmit={async (newVals) => {+ console.log('debug', newVals)+ try {+ if (!selectedReport) return+ if (!selectedReport.id) return+ if (!selectedReport.project_id) return++ await updateReport.mutateAsync({+ projectRef: ref,+ payload: {+ ...selectedReport,+ project_id: selectedReport.project_id,+ id: selectedReport.id,+ name: newVals.name,+ description: newVals.description || '',+ },+ })+ toast.success('Report updated')+ setShowUpdateReportModal(false)+ } catch (error) {+ toast.error(`Failed to update report. Check console for more details.`)+ console.error(error)+ }+ }}+ onCancel={() => setShowUpdateReportModal(false)}+ visible={showUpdateReportModal}+ initialValues={{+ name: selectedReport?.name || '',+ description: selectedReport?.description || '',+ }}+ />+ <ConfirmationModal+ header="Delete custom report"+ buttonLabel="Delete report"+ buttonLoadingLabel="Deleting report"+ size="medium"+ loading={deleteReport.isLoading}+ visible={deleteModalOpen}+ onSelectConfirm={async () => {+ if (selectedReport) {+ if (!selectedReport.id) return+ await deleteReport.mutateAsync({+ projectRef: ref,+ ids: [selectedReport.id],+ })+ toast.success('Report deleted')+ router.push(`/project/${ref}/reports`)+ }+ setDeleteModalOpen(false)+ }}+ onSelectCancel={() => setDeleteModalOpen(false)}+ >+ <Modal.Content>+ <div className="my-6">+ <div className="text-sm text-foreground-light grid gap-4">+ <div className="grid gap-1">+ <p>Are you sure you want to delete '{selectedReport?.name}'?</p>+ </div>+ </div>+ </div>+ </Modal.Content>+ </ConfirmationModal>+ <CreateReportModal+ visible={showNewReportModal}+ onCancel={() => {+ setShowNewReportModal(false)+ }}+ afterSubmit={() => {+ setShowNewReportModal(false)+ }}+ />+ </div>+ )}+ </Menu>+ )+}++export default ReportsMenudiff --git a/apps/studio/pages/project/[ref]/reports/[id].tsx b/apps/studio/pages/project/[ref]/reports/[id].tsxindex 01101070ba6..9d61091362b 100644--- a/apps/studio/pages/project/[ref]/reports/[id].tsx+++ b/apps/studio/pages/project/[ref]/reports/[id].tsx@@ -6,7 +6,7 @@ import { NextPageWithLayout } from 'types'const PageLayout: NextPageWithLayout = () => (<>- <div className="1xl:px-28 mx-auto flex flex-col gap-4 px-5 py-6 lg:px-16 xl:px-24 2xl:px-32">+ <div className="mx-auto flex flex-col gap-4 p-3"><Reports /></div><EditReportModal />diff --git a/apps/studio/pages/project/[ref]/reports/index.tsx b/apps/studio/pages/project/[ref]/reports/index.tsxindex 0b98abcba3e..05111098d05 100644--- a/apps/studio/pages/project/[ref]/reports/index.tsx+++ b/apps/studio/pages/project/[ref]/reports/index.tsx@@ -11,6 +11,7 @@ import { useCheckPermissions, useStore } from 'hooks'import { useProfile } from 'lib/profile'import { useProjectContentStore } from 'stores/projectContentStore'import { NextPageWithLayout } from 'types'+import { CreateReportModal } from 'components/interfaces/Reports/Reports.CreateReportModal'export const UserReportPage: NextPageWithLayout = () => {const [loading, setLoading] = useState(true)@@ -20,6 +21,7 @@ export const UserReportPage: NextPageWithLayout = () => {const { profile } = useProfile()const { ui } = useStore()+ const [showCreateReportModal, setShowCreateReportModal] = useState(false)const contentStore = useProjectContentStore(ref)const canCreateReport = useCheckPermissions(PermissionAction.CREATE, 'user_content', {@@ -47,28 +49,34 @@ export const UserReportPage: NextPageWithLayout = () => {{loading ? (<Loading />) : (- <ProductEmptyState- title="Reports"- ctaButtonLabel="Create report"- onClickCta={() => {- try {- createReport({ router })- } catch (error: any) {- ui.setNotification({- category: 'error',- message: `Failed to create report: ${error.message}`,- })- }- }}- disabled={!canCreateReport}- disabledMessage="You need additional permissions to create a report"- >- <p className="text-foreground-light text-sm">Create custom reports for your projects.</p>- <p className="text-foreground-light text-sm">- Get a high level overview of your network traffic, user actions, and infrastructure- health.- </p>- </ProductEmptyState>+ <>+ <ProductEmptyState+ title="Reports"+ ctaButtonLabel="New custom report"+ onClickCta={() => {+ setShowCreateReportModal(true)+ }}+ disabled={!canCreateReport}+ disabledMessage="You need additional permissions to create a report"+ >+ <p className="text-foreground-light text-sm">+ Create custom reports for your projects.+ </p>+ <p className="text-foreground-light text-sm">+ Get a high level overview of your network traffic, user actions, and infrastructure+ health.+ </p>+ </ProductEmptyState>+ <CreateReportModal+ visible={showCreateReportModal}+ onCancel={() => {+ setShowCreateReportModal(false)+ }}+ afterSubmit={() => {+ setShowCreateReportModal(false)+ }}+ />+ </>)}</div>)