:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-catalog): add catalog scene with metrics tab (#73970)
Thiago Salvatorece4dd1ac7935
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 266f8b819c22..95cbef65b0d5 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -51,6 +51,7 @@ export const productScenes: Record<string, () => Promise<any>> = {import('../../products/customer_analytics/frontend/scenes/CustomerJourneyBuilderScene/CustomerJourneyBuilderScene'),CustomerJourneyTemplates: () =>import('../../products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/CustomerJourneyTemplatesScene'),+ DataCatalog: () => import('../../products/data_catalog/frontend/DataCatalogScene'),DataOps: () => import('../../products/data_warehouse/DataWarehouseScene'),Models: () => import('../../frontend/src/scenes/models/ModelsScene'),NodeDetail: () => import('../../frontend/src/scenes/models/NodeDetailScene'),diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 613773f107ca..1f56a0ec98bd 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -91,6 +91,13 @@"type": "dashboard","intents": ["product_analytics"]},+ {+ "path": "Data catalog",+ "category": "Analytics",+ "iconType": "data_warehouse",+ "type": null,+ "intents": ["data_catalog"]+ },{"path": "SQL editor","category": "Analytics",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex e0f728f805a4..75bf918c7c4e 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -107,6 +107,7 @@ export const productRoutes: Record<string, [string, string]> = {'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],'/customer_analytics/journeys': ['CustomerAnalytics', 'customerAnalyticsJourneys'],'/customer_analytics/configuration': ['CustomerAnalyticsConfiguration', 'customerAnalyticsConfiguration'],+ '/data-catalog': ['DataCatalog', 'dataCatalog'],'/data-ops': ['DataOps', 'dataOps'],'/models': ['Models', 'models'],'/models/dags': ['Models', 'models'],@@ -531,6 +532,13 @@ export const productConfiguration: Record<string, any> = {CustomerAnalyticsConfiguration: { projectBased: true, name: 'Customer analytics configuration' },CustomerJourneyBuilder: { projectBased: true, name: 'New journey' },CustomerJourneyTemplates: { projectBased: true, name: 'New journey' },+ DataCatalog: {+ projectBased: true,+ name: 'Data catalog',+ layout: 'app-container',+ iconType: 'data_warehouse',+ description: 'Review and manage governed metrics, certifications, and relationships for your data.',+ },DataOps: {name: 'Data ops',projectBased: true,@@ -982,6 +990,7 @@ export const productUrls = {dashboardSubscription: (id: string | number, subscriptionId: string): string =>`/dashboard/${id}/subscriptions/${subscriptionId}`,sharedDashboard: (shareToken: string): string => `/shared_dashboard/${shareToken}`,+ dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,dataOps: (tab?: string, dagId?: string): string => {const params = new URLSearchParams()if (tab) {@@ -1778,6 +1787,16 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [sceneKey: 'Dashboards',sceneKeys: ['Dashboard', 'Dashboards'],},+ {+ path: 'Data catalog',+ intents: [ProductKey.DATA_CATALOG],+ category: ProductItemCategory.ANALYTICS,+ iconType: 'data_warehouse',+ href: urls.dataCatalog(),+ flag: FEATURE_FLAGS.PRODUCT_DATA_CATALOG,+ sceneKey: 'DataCatalog',+ sceneKeys: ['DataCatalog'],+ },{path: 'Data warehouse',displayLabel: 'Data ops',diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 8be2a31c7013..192917c2833f 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -34943,6 +34943,7 @@"comments","conversations","customer_analytics",+ "data_catalog","data_warehouse","data_warehouse_saved_queries","early_access_features",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex b44cf63e5c60..f2f55eacfd11 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8625,6 +8625,7 @@ export enum ProductKey {COMMENTS = 'comments',CONVERSATIONS = 'conversations',CUSTOMER_ANALYTICS = 'customer_analytics',+ DATA_CATALOG = 'data_catalog',DATA_WAREHOUSE = 'data_warehouse',DATA_WAREHOUSE_SAVED_QUERY = 'data_warehouse_saved_queries',EARLY_ACCESS_FEATURES = 'early_access_features',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex cc88c30dcf98..279659ba314b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2772,7 +2772,39 @@ importers:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))- products/data_catalog: {}+ products/data_catalog:+ dependencies:+ '@posthog/icons':+ specifier: 'catalog:'+ '@types/react':+ specifier: 18.3.27+ version: 18.3.27+ clsx:+ specifier: '*'+ version: 2.1.1+ fast-equals:+ specifier: 'catalog:'+ version: 6.0.1+ fuse.js:+ specifier: '*'+ version: 7.3.0+ kea:+ specifier: 'catalog:'+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-router:+ specifier: 'catalog:'+ version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ react:+ specifier: 18.3.1+ version: 18.3.1+ devDependencies:+ '@storybook/react':+ specifier: 'catalog:'+ version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])products/data_modeling:dependencies:diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 5ad9b49c5beb..d9984250203c 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3386,6 +3386,7 @@ class ProductKey(StrEnum):COMMENTS = "comments"CONVERSATIONS = "conversations"CUSTOMER_ANALYTICS = "customer_analytics"+ DATA_CATALOG = "data_catalog"DATA_WAREHOUSE = "data_warehouse"DATA_WAREHOUSE_SAVED_QUERIES = "data_warehouse_saved_queries"EARLY_ACCESS_FEATURES = "early_access_features"diff --git a/products/data_catalog/frontend/DataCatalogScene.tsx b/products/data_catalog/frontend/DataCatalogScene.tsxnew file mode 100644index 000000000000..f7fe3cbea565--- /dev/null+++ b/products/data_catalog/frontend/DataCatalogScene.tsx@@ -0,0 +1,85 @@+import { BindLogic, useActions, useValues } from 'kea'++import { IconPlusSmall } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductKey } from '~/queries/schema/schema-general'++import { NewMetricModal } from './components/NewMetricModal'+import { DataCatalogTab, dataCatalogSceneLogic } from './dataCatalogSceneLogic'+import { metricsLogic } from './metricsLogic'+import { MetricsTab } from './tabs/MetricsTab'++export const scene: SceneExport = {+ component: DataCatalogScene,+ logic: dataCatalogSceneLogic,+ productKey: ProductKey.DATA_CATALOG,+}++function TabPlaceholder({ label }: { label: string }): JSX.Element {+ return <p className="text-secondary">{label} are coming soon.</p>+}++export function DataCatalogScene(): JSX.Element {+ const { activeTab } = useValues(dataCatalogSceneLogic)+ const { setActiveTab } = useActions(dataCatalogSceneLogic)+ const { openNewMetricModal } = useActions(metricsLogic)++ const tabs: LemonTab<DataCatalogTab>[] = [+ {+ key: 'metrics',+ label: 'Metrics',+ content: <MetricsTab />,+ link: urls.dataCatalog(),+ },+ {+ key: 'relationships',+ label: 'Relationships',+ content: <TabPlaceholder label="Relationships" />,+ link: urls.dataCatalog('relationships'),+ },+ {+ key: 'certifications',+ label: 'Certifications',+ content: <TabPlaceholder label="Certifications" />,+ link: urls.dataCatalog('certifications'),+ },+ ]++ return (+ <BindLogic logic={metricsLogic} props={{}}>+ <SceneContent>+ <SceneTitleSection+ name="Data catalog"+ description="Review and manage governed metrics, certifications, and relationships for your data."+ resourceType={{ type: 'data_warehouse' }}+ actions={+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlusSmall />}+ onClick={openNewMetricModal}+ data-attr="data-catalog-new-metric-button"+ >+ New metric+ </LemonButton>+ }+ />+ <LemonTabs+ activeKey={activeTab}+ onChange={setActiveTab}+ data-attr="data-catalog-tabs"+ tabs={tabs}+ sceneInset+ />+ <NewMetricModal />+ </SceneContent>+ </BindLogic>+ )+}diff --git a/products/data_catalog/frontend/common.ts b/products/data_catalog/frontend/common.tsnew file mode 100644index 000000000000..8843fdb49b15--- /dev/null+++ b/products/data_catalog/frontend/common.ts@@ -0,0 +1,24 @@+export const METRIC_NAME_REGEX = /^[A-Za-z][A-Za-z0-9_]*$/++export function humanizeDefinitionKind(kind: string | null): string {+ if (!kind) {+ return 'Stub'+ }+ if (kind === 'HogQLQuery') {+ return 'SQL'+ }+ if (kind === 'MarkdownDefinition') {+ return 'Markdown'+ }+ return kind+}++export function validateMetricName(name: string): string | undefined {+ if (!name) {+ return 'Name is required'+ }+ if (!METRIC_NAME_REGEX.test(name)) {+ return 'Use letters, numbers, and underscores, starting with a letter'+ }+ return undefined+}diff --git a/products/data_catalog/frontend/components/NewMetricModal.tsx b/products/data_catalog/frontend/components/NewMetricModal.tsxnew file mode 100644index 000000000000..1caf215fe592--- /dev/null+++ b/products/data_catalog/frontend/components/NewMetricModal.tsx@@ -0,0 +1,155 @@+import { useActions, useValues } from 'kea'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { LemonModal } from 'lib/lemon-ui/LemonModal'+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'+import { LemonTextAreaMarkdown } from 'lib/lemon-ui/LemonTextArea/LemonTextAreaMarkdown'++import { validateMetricName } from '../common'+import { metricsLogic, NewMetricDefinitionType } from '../metricsLogic'++// The Text (markdown) option is hidden until its editor UI is polished.+const DEFINITION_TYPE_OPTIONS: { value: NewMetricDefinitionType; label: string }[] = [+ { value: 'sql', label: 'SQL' },+ { value: 'insight', label: 'Insight' },+]++export function NewMetricModal(): JSX.Element {+ const { newMetricModalOpen, newMetricForm, isCreatingMetric, savedInsights, savedInsightsLoading } =+ useValues(metricsLogic)+ const { setNewMetricForm, createMetric, closeNewMetricModal, openSqlEditorForNewMetric, setInsightSearch } =+ useActions(metricsLogic)++ const nameError = validateMetricName(newMetricForm.name.trim())+ const submitDisabledReason = nameError+ ? nameError+ : !newMetricForm.description.trim()+ ? 'Add a description'+ : newMetricForm.definitionType === 'sql'+ ? 'Create SQL metrics from the SQL editor'+ : newMetricForm.definitionType === 'insight' && !newMetricForm.sourceInsightShortId+ ? 'Choose an insight'+ : newMetricForm.definitionType === 'markdown' && !newMetricForm.markdown.trim()+ ? 'Add the markdown definition'+ : undefined++ return (+ <LemonModal isOpen={newMetricModalOpen} onClose={closeNewMetricModal} width={640} title="New metric">+ <LemonModal.Content>+ <div className="flex flex-col gap-4">+ <LemonField.Pure+ label="Name"+ error={newMetricForm.name.trim() ? nameError : undefined}+ info="A unique identifier for the metric, like monthly_active_users."+ >+ <LemonInput+ value={newMetricForm.name}+ onChange={(name) => setNewMetricForm({ name })}+ placeholder="monthly_active_users"+ autoFocus+ />+ </LemonField.Pure>++ <LemonField.Pure label="Display name" info="A human-friendly name shown in the catalog.">+ <LemonInput+ value={newMetricForm.display_name}+ onChange={(display_name) => setNewMetricForm({ display_name })}+ placeholder="Monthly active users"+ />+ </LemonField.Pure>++ <LemonField.Pure label="Description">+ <LemonTextArea+ value={newMetricForm.description}+ onChange={(description) => setNewMetricForm({ description })}+ placeholder="What this metric measures and how to read it"+ minRows={2}+ />+ </LemonField.Pure>++ <LemonField.Pure label="Unit" info="How the result is measured, like users, dollars, or percent.">+ <LemonInput+ value={newMetricForm.unit}+ onChange={(unit) => setNewMetricForm({ unit })}+ placeholder="users"+ />+ </LemonField.Pure>++ <LemonField.Pure label="Definition">+ <LemonSegmentedButton+ value={newMetricForm.definitionType}+ onChange={(definitionType) => setNewMetricForm({ definitionType })}+ options={DEFINITION_TYPE_OPTIONS}+ />+ </LemonField.Pure>++ {newMetricForm.definitionType === 'markdown' && (+ <LemonField.Pure label="Text">+ <LemonTextAreaMarkdown+ value={newMetricForm.markdown}+ onChange={(markdown) => setNewMetricForm({ markdown })}+ placeholder="Numbered steps describing how to calculate this metric"+ />+ </LemonField.Pure>+ )}++ {newMetricForm.definitionType === 'sql' && (+ <LemonBanner type="info">+ <div className="flex flex-col items-start gap-2">+ <span>Write the query in the SQL editor, then use Save as metric to define it.</span>+ <LemonButton+ type="secondary"+ onClick={openSqlEditorForNewMetric}+ data-attr="data-catalog-new-metric-open-sql-editor"+ >+ Open SQL editor+ </LemonButton>+ </div>+ </LemonBanner>+ )}++ {newMetricForm.definitionType === 'insight' && (+ <LemonField.Pure+ label="Insight"+ info="The metric snapshots the insight's query and tracks drift against it."+ >+ <LemonInputSelect+ mode="single"+ value={newMetricForm.sourceInsightShortId ? [newMetricForm.sourceInsightShortId] : []}+ onChange={(values) => setNewMetricForm({ sourceInsightShortId: values[0] || '' })}+ options={savedInsights.map((insight) => ({+ key: insight.short_id,+ label: insight.label,+ }))}+ loading={savedInsightsLoading}+ onInputChange={setInsightSearch}+ placeholder="Search insights"+ data-attr="data-catalog-new-metric-insight"+ />+ </LemonField.Pure>+ )}+ </div>+ </LemonModal.Content>++ <LemonModal.Footer>+ <LemonButton type="secondary" onClick={closeNewMetricModal} disabled={isCreatingMetric}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={createMetric}+ loading={isCreatingMetric}+ disabledReason={submitDisabledReason}+ data-attr="data-catalog-create-metric-submit"+ >+ Create metric+ </LemonButton>+ </LemonModal.Footer>+ </LemonModal>+ )+}diff --git a/products/data_catalog/frontend/dataCatalogSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogSceneLogic.tsxnew file mode 100644index 000000000000..378995a926d5--- /dev/null+++ b/products/data_catalog/frontend/dataCatalogSceneLogic.tsx@@ -0,0 +1,48 @@+import { MakeLogicType, actions, kea, path, reducers } from 'kea'+import { actionToUrl, urlToAction } from 'kea-router'++import { urls } from 'scenes/urls'++export type DataCatalogTab = 'metrics' | 'relationships' | 'certifications'++export const DATA_CATALOG_TABS: DataCatalogTab[] = ['metrics', 'relationships', 'certifications']++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataCatalogSceneLogicValues {+ activeTab: DataCatalogTab+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataCatalogSceneLogicActions {+ setActiveTab: (activeTab: DataCatalogTab) => {+ activeTab: DataCatalogTab+ }+}++export type dataCatalogSceneLogicType = MakeLogicType<dataCatalogSceneLogicValues, dataCatalogSceneLogicActions>++export const dataCatalogSceneLogic = kea<dataCatalogSceneLogicType>([+ path(['products', 'data_catalog', 'frontend', 'dataCatalogSceneLogic']),+ actions({+ setActiveTab: (activeTab: DataCatalogTab) => ({ activeTab }),+ }),+ reducers({+ activeTab: [+ 'metrics' as DataCatalogTab,+ {+ setActiveTab: (_, { activeTab }) => activeTab,+ },+ ],+ }),+ actionToUrl(({ values }) => ({+ setActiveTab: () => urls.dataCatalog(values.activeTab === 'metrics' ? undefined : values.activeTab),+ })),+ urlToAction(({ actions, values }) => ({+ [urls.dataCatalog()]: (_, searchParams) => {+ const tab = DATA_CATALOG_TABS.includes(searchParams.tab) ? searchParams.tab : 'metrics'+ if (tab !== values.activeTab) {+ actions.setActiveTab(tab)+ }+ },+ })),+])diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.tsnew file mode 100644index 000000000000..aea6e54eb9c4--- /dev/null+++ b/products/data_catalog/frontend/metricsLogic.test.ts@@ -0,0 +1,142 @@+import { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ dataCatalogMetricsApproveCreate,+ dataCatalogMetricsCreate,+ dataCatalogMetricsDestroy,+ dataCatalogMetricsList,+} from './generated/api'+import type { DataCatalogMetricApi } from './generated/api.schemas'+import { metricsLogic } from './metricsLogic'++jest.mock('lib/api', () => {+ class ApiError extends Error {+ status?: number+ detail: string | null+ constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {+ super(message)+ this.status = status+ this.detail = data?.detail ?? null+ }+ }+ return {+ __esModule: true,+ default: { insights: { list: jest.fn().mockResolvedValue({ results: [] }) } },+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError,+ }+})++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },+}))++jest.mock('./generated/api', () => ({+ dataCatalogMetricsList: jest.fn(),+ dataCatalogMetricsCreate: jest.fn(),+ dataCatalogMetricsApproveCreate: jest.fn(),+ dataCatalogMetricsRefreshFromInsightCreate: jest.fn(),+ dataCatalogMetricsDestroy: jest.fn(),+}))++function buildMetric(overrides: Partial<DataCatalogMetricApi> = {}): DataCatalogMetricApi {+ return {+ id: 'metric-1',+ name: 'weekly_active_users',+ description: 'Weekly active users',+ definition_kind: 'HogQLQuery',+ status: 'proposed',+ is_drifted: false,+ owner: null,+ ...overrides,+ } as DataCatalogMetricApi+}++describe('metricsLogic', () => {+ let logic: ReturnType<typeof metricsLogic.build>++ beforeEach(async () => {+ jest.clearAllMocks()+ ;(dataCatalogMetricsList as jest.Mock).mockResolvedValue({ results: [buildMetric()] })+ initKeaTests()+ logic = metricsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadMetricsSuccess'])+ })++ it('replaces the row with the response when approve succeeds', async () => {+ ;(dataCatalogMetricsApproveCreate as jest.Mock).mockResolvedValue(buildMetric({ status: 'approved' }))++ logic.actions.approveMetric('weekly_active_users')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.allMetrics[0].status).toEqual('approved')+ })++ it('leaves the row untouched and surfaces refresh when approve returns 409', async () => {+ ;(dataCatalogMetricsApproveCreate as jest.Mock).mockRejectedValue(new ApiError('drifted', 409))++ logic.actions.approveMetric('weekly_active_users')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.allMetrics[0].status).toEqual('proposed')+ const errorCall = (lemonToast.error as jest.Mock).mock.calls.at(-1)+ expect(errorCall?.[1]?.button?.label).toEqual('Refresh from insight')+ })++ it('guards double-submit and closes the modal when create succeeds', async () => {+ let resolveCreate: (metric: DataCatalogMetricApi) => void = () => {}+ ;(dataCatalogMetricsCreate as jest.Mock).mockReturnValue(+ new Promise((resolve) => {+ resolveCreate = resolve+ })+ )++ logic.actions.openNewMetricModal()+ logic.actions.setNewMetricForm({+ name: 'monthly_active_users',+ description: 'Monthly active users',+ definitionType: 'insight',+ sourceInsightShortId: 'abc123',+ })++ logic.actions.createMetric()+ logic.actions.createMetric()+ expect(dataCatalogMetricsCreate).toHaveBeenCalledTimes(1)++ resolveCreate(buildMetric({ id: 'metric-2', name: 'monthly_active_users' }))+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.newMetricModalOpen).toEqual(false)+ expect(logic.values.allMetrics.map((metric) => metric.name)).toContain('monthly_active_users')+ })++ it('does not create a SQL metric from the modal', async () => {+ logic.actions.openNewMetricModal()+ logic.actions.setNewMetricForm({+ name: 'sql_metric',+ description: 'Defined in the SQL editor',+ definitionType: 'sql',+ })++ logic.actions.createMetric()+ await expectLogic(logic).toFinishAllListeners()++ expect(dataCatalogMetricsCreate).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith('Create SQL metrics from the SQL editor.')+ expect(logic.values.newMetricModalOpen).toEqual(true)+ })++ it('removes the row when delete succeeds', async () => {+ ;(dataCatalogMetricsDestroy as jest.Mock).mockResolvedValue(undefined)++ logic.actions.deleteMetric('weekly_active_users')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.allMetrics).toHaveLength(0)+ })+})diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsxnew file mode 100644index 000000000000..05628e94d61b--- /dev/null+++ b/products/data_catalog/frontend/metricsLogic.tsx@@ -0,0 +1,411 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import api, { ApiConfig, ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { createFuse } from 'lib/utils/fuseSearch'+import { urls } from 'scenes/urls'++import {+ dataCatalogMetricsApproveCreate,+ dataCatalogMetricsCreate,+ dataCatalogMetricsDestroy,+ dataCatalogMetricsList,+ dataCatalogMetricsRefreshFromInsightCreate,+} from './generated/api'+import type { DataCatalogMetricApi } from './generated/api.schemas'++export type MetricStatusFilter = 'all' | 'proposed' | 'approved'++export interface MetricsFilters {+ search: string+ status: MetricStatusFilter+}++export const DEFAULT_METRICS_FILTERS: MetricsFilters = {+ search: '',+ status: 'all',+}++export type NewMetricDefinitionType = 'markdown' | 'insight' | 'sql'++export interface NewMetricForm {+ name: string+ display_name: string+ description: string+ unit: string+ definitionType: NewMetricDefinitionType+ markdown: string+ sourceInsightShortId: string+}++export const EMPTY_NEW_METRIC_FORM: NewMetricForm = {+ name: '',+ display_name: '',+ description: '',+ unit: '',+ definitionType: 'sql',+ markdown: '',+ sourceInsightShortId: '',+}++export interface SavedInsightOption {+ short_id: string+ label: string+}++const MARKDOWN_DEFINITION_KIND = 'MarkdownDefinition'++function projectId(): string {+ return String(ApiConfig.getCurrentTeamId())+}++function buildMarkdownDefinition(markdown: string): Record<string, unknown> {+ return { kind: MARKDOWN_DEFINITION_KIND, markdown }+}++function apiErrorDetail(error: unknown): string | null {+ return error instanceof ApiError ? error.detail : null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsLogicValues {+ actionsInFlight: Record<string, boolean>+ allMetrics: DataCatalogMetricApi[]+ allMetricsLoading: boolean+ filters: MetricsFilters+ insightSearch: string+ isCreatingMetric: boolean+ metrics: DataCatalogMetricApi[]+ newMetricForm: NewMetricForm+ newMetricModalOpen: boolean+ proposedCount: number+ savedInsights: SavedInsightOption[]+ savedInsightsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsLogicActions {+ approveMetric: (name: string) => {+ name: string+ }+ closeNewMetricModal: () => {+ value: true+ }+ createMetric: () => {+ value: true+ }+ deleteMetric: (name: string) => {+ name: string+ }+ loadMetrics: () => any+ loadMetricsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMetricsSuccess: (+ allMetrics: DataCatalogMetricApi[],+ payload?: any+ ) => {+ allMetrics: DataCatalogMetricApi[]+ payload?: any+ }+ loadSavedInsights: () => {+ value: true+ }+ loadSavedInsightsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSavedInsightsSuccess: (+ savedInsights: {+ label: string+ short_id: string+ }[],+ payload?: {+ value: true+ }+ ) => {+ savedInsights: {+ label: string+ short_id: string+ }[]+ payload?: {+ value: true+ }+ }+ openNewMetricModal: () => {+ value: true+ }+ openSqlEditorForNewMetric: () => {+ value: true+ }+ refreshMetricFromInsight: (name: string) => {+ name: string+ }+ setActionInFlight: (+ name: string,+ inFlight: boolean+ ) => {+ inFlight: boolean+ name: string+ }+ setCreatingMetric: (creating: boolean) => {+ creating: boolean+ }+ setFilters: (filters: Partial<MetricsFilters>) => {+ filters: Partial<MetricsFilters>+ }+ setInsightSearch: (search: string) => {+ search: string+ }+ setNewMetricForm: (form: Partial<NewMetricForm>) => {+ form: Partial<NewMetricForm>+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ metrics: (allMetrics: DataCatalogMetricApi[], filters: MetricsFilters) => DataCatalogMetricApi[]+ proposedCount: (allMetrics: DataCatalogMetricApi[]) => number+ }+}++export type metricsLogicType = MakeLogicType<+ metricsLogicValues,+ metricsLogicActions,+ Record<string, any>,+ metricsLogicMeta+>++export const metricsLogic = kea<metricsLogicType>([+ path(['products', 'data_catalog', 'frontend', 'metricsLogic']),+ actions({+ setFilters: (filters: Partial<MetricsFilters>) => ({ filters }),+ openNewMetricModal: true,+ openSqlEditorForNewMetric: true,+ closeNewMetricModal: true,+ setNewMetricForm: (form: Partial<NewMetricForm>) => ({ form }),+ setInsightSearch: (search: string) => ({ search }),+ loadSavedInsights: true,+ createMetric: true,+ setCreatingMetric: (creating: boolean) => ({ creating }),+ approveMetric: (name: string) => ({ name }),+ refreshMetricFromInsight: (name: string) => ({ name }),+ deleteMetric: (name: string) => ({ name }),+ setActionInFlight: (name: string, inFlight: boolean) => ({ name, inFlight }),+ }),+ loaders(({ values }) => ({+ allMetrics: [+ [] as DataCatalogMetricApi[],+ {+ loadMetrics: async () => {+ const response = await dataCatalogMetricsList(projectId())+ return response.results || []+ },+ },+ ],+ savedInsights: [+ [] as SavedInsightOption[],+ {+ // Search server-side so insights beyond the first page are still selectable.+ loadSavedInsights: async (_, breakpoint) => {+ await breakpoint(300)+ const response = await api.insights.list({+ saved: true,+ basic: true,+ limit: 100,+ search: values.insightSearch || undefined,+ })+ breakpoint()+ return (response.results || [])+ .filter((insight) => !!insight.short_id)+ .map((insight) => ({+ short_id: insight.short_id as string,+ label: insight.name || insight.derived_name || (insight.short_id as string),+ }))+ },+ },+ ],+ })),+ reducers({+ filters: [+ DEFAULT_METRICS_FILTERS as MetricsFilters,+ {+ setFilters: (state, { filters }) => ({ ...state, ...filters }),+ },+ ],+ newMetricModalOpen: [+ false,+ {+ openNewMetricModal: () => true,+ closeNewMetricModal: () => false,+ },+ ],+ newMetricForm: [+ EMPTY_NEW_METRIC_FORM as NewMetricForm,+ {+ setNewMetricForm: (state, { form }) => ({ ...state, ...form }),+ openNewMetricModal: () => EMPTY_NEW_METRIC_FORM,+ closeNewMetricModal: () => EMPTY_NEW_METRIC_FORM,+ },+ ],+ isCreatingMetric: [+ false,+ {+ setCreatingMetric: (_, { creating }) => creating,+ },+ ],+ actionsInFlight: [+ {} as Record<string, boolean>,+ {+ setActionInFlight: (state, { name, inFlight }) => ({ ...state, [name]: inFlight }),+ },+ ],+ insightSearch: [+ '',+ {+ setInsightSearch: (_, { search }) => search,+ openNewMetricModal: () => '',+ closeNewMetricModal: () => '',+ },+ ],+ }),+ selectors({+ metrics: [+ (s) => [s.allMetrics, s.filters],+ (allMetrics: DataCatalogMetricApi[], filters: MetricsFilters) => {+ let results = allMetrics+ if (filters.status !== 'all') {+ results = results.filter((metric) => metric.status === filters.status)+ }+ if (filters.search) {+ const fuse = createFuse<DataCatalogMetricApi>(results, {+ keys: ['name', 'display_name', 'description'],+ threshold: 0.3,+ })+ results = fuse.search(filters.search).map((result) => result.item)+ }+ return results+ },+ ],+ proposedCount: [+ (s) => [s.allMetrics],+ (allMetrics: DataCatalogMetricApi[]) => allMetrics.filter((metric) => metric.status === 'proposed').length,+ ],+ }),+ listeners(({ values, actions }) => ({+ openNewMetricModal: () => actions.loadSavedInsights(),+ setInsightSearch: () => actions.loadSavedInsights(),+ openSqlEditorForNewMetric: () => {+ actions.closeNewMetricModal()+ router.actions.push(urls.sqlEditor({ source: 'metric' }))+ },+ createMetric: async () => {+ if (values.isCreatingMetric) {+ return+ }+ const form = values.newMetricForm+ if (form.definitionType === 'sql') {+ // SQL metrics are defined from the SQL editor, so the else branch below only handles markdown.+ lemonToast.error('Create SQL metrics from the SQL editor.')+ return+ }+ actions.setCreatingMetric(true)+ try {+ const created = await dataCatalogMetricsCreate(projectId(), {+ name: form.name,+ display_name: form.display_name || undefined,+ description: form.description,+ unit: form.unit || undefined,+ ...(form.definitionType === 'insight'+ ? { source_insight_short_id: form.sourceInsightShortId }+ : { definition: buildMarkdownDefinition(form.markdown) }),+ created_source: 'user',+ })+ actions.loadMetricsSuccess([created, ...values.allMetrics])+ actions.closeNewMetricModal()+ lemonToast.success('Metric created')+ } catch (error) {+ lemonToast.error(+ apiErrorDetail(error) || 'Could not create the metric. Check the fields and try again.'+ )+ } finally {+ actions.setCreatingMetric(false)+ }+ },+ approveMetric: async ({ name }) => {+ if (values.actionsInFlight[name]) {+ return+ }+ actions.setActionInFlight(name, true)+ try {+ const approved = await dataCatalogMetricsApproveCreate(projectId(), name)+ actions.loadMetricsSuccess(+ values.allMetrics.map((metric) => (metric.name === name ? approved : metric))+ )+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ lemonToast.error(+ 'This metric has drifted from its source insight and cannot be approved. Refresh it first.',+ {+ button: {+ label: 'Refresh from insight',+ action: () => actions.refreshMetricFromInsight(name),+ },+ }+ )+ } else {+ lemonToast.error(apiErrorDetail(error) || 'Could not approve the metric. Try again.')+ }+ } finally {+ actions.setActionInFlight(name, false)+ }+ },+ refreshMetricFromInsight: async ({ name }) => {+ if (values.actionsInFlight[name]) {+ return+ }+ actions.setActionInFlight(name, true)+ try {+ const refreshed = await dataCatalogMetricsRefreshFromInsightCreate(projectId(), name)+ actions.loadMetricsSuccess(+ values.allMetrics.map((metric) => (metric.name === name ? refreshed : metric))+ )+ lemonToast.success('Metric refreshed from its source insight')+ } catch (error) {+ lemonToast.error(+ apiErrorDetail(error) || 'Could not refresh the metric from its source insight. Try again.'+ )+ } finally {+ actions.setActionInFlight(name, false)+ }+ },+ deleteMetric: async ({ name }) => {+ if (values.actionsInFlight[name]) {+ return+ }+ actions.setActionInFlight(name, true)+ try {+ await dataCatalogMetricsDestroy(projectId(), name)+ actions.loadMetricsSuccess(values.allMetrics.filter((metric) => metric.name !== name))+ lemonToast.success('Metric deleted')+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not delete the metric. Try again.')+ } finally {+ actions.setActionInFlight(name, false)+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadMetrics()+ }),+])diff --git a/products/data_catalog/frontend/tabs/MetricsTab.tsx b/products/data_catalog/frontend/tabs/MetricsTab.tsxnew file mode 100644index 000000000000..d122542da778--- /dev/null+++ b/products/data_catalog/frontend/tabs/MetricsTab.tsx@@ -0,0 +1,218 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import { LemonButton, LemonDialog } from '@posthog/lemon-ui'++import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { createdAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { LemonTag } from 'lib/lemon-ui/LemonTag'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import { ProductKey } from '~/queries/schema/schema-general'++import { humanizeDefinitionKind } from '../common'+import type { DataCatalogMetricApi } from '../generated/api.schemas'+import { MetricStatusFilter, metricsLogic } from '../metricsLogic'++const STATUS_FILTER_OPTIONS: { value: MetricStatusFilter; label: string }[] = [+ { value: 'all', label: 'All' },+ { value: 'proposed', label: 'Proposed' },+ { value: 'approved', label: 'Approved' },+]++function StatusTag({ metric }: { metric: DataCatalogMetricApi }): JSX.Element {+ return (+ <div className="flex items-center gap-1">+ <LemonTag type={metric.status === 'approved' ? 'success' : 'warning'}>{metric.status}</LemonTag>+ {metric.is_drifted && <LemonTag type="danger">Drifted</LemonTag>}+ </div>+ )+}++function SourceTag({ metric }: { metric: DataCatalogMetricApi }): JSX.Element {+ if (metric.created_source !== 'ai_generated') {+ return <span className="text-secondary">User</span>+ }+ const confidencePercent = metric.confidence != null ? `${Math.round(metric.confidence * 100)}%` : 'unknown'+ return (+ <Tooltip+ title={+ <div className="flex flex-col gap-1">+ <span>Confidence: {confidencePercent}</span>+ {metric.ai_model && <span>Model: {metric.ai_model}</span>}+ {metric.reasoning && <span>{metric.reasoning}</span>}+ </div>+ }+ >+ <LemonTag type="completion">AI</LemonTag>+ </Tooltip>+ )+}++export function MetricsTab(): JSX.Element {+ const { metrics, allMetrics, allMetricsLoading, filters, actionsInFlight } = useValues(metricsLogic)+ const { setFilters, loadMetrics, approveMetric, refreshMetricFromInsight, deleteMetric, openNewMetricModal } =+ useActions(metricsLogic)++ const confirmDelete = (metric: DataCatalogMetricApi): void => {+ LemonDialog.open({+ title: 'Delete metric?',+ content: <div className="text-sm text-secondary">Deleting {metric.name} cannot be undone.</div>,+ primaryButton: {+ children: 'Delete',+ type: 'primary',+ status: 'danger',+ onClick: () => deleteMetric(metric.name),+ },+ secondaryButton: { children: 'Cancel', type: 'tertiary' },+ })+ }++ if (!allMetricsLoading && allMetrics.length === 0) {+ return (+ <ProductIntroduction+ productName="Data catalog"+ productKey={ProductKey.DATA_CATALOG}+ thingName="metric"+ description="Metrics give your team one canonical definition for a number. Define one from SQL, an insight, or written instructions."+ isEmpty+ action={openNewMetricModal}+ />+ )+ }++ const columns: LemonTableColumns<DataCatalogMetricApi> = [+ {+ title: 'Name',+ key: 'name',+ dataIndex: 'name',+ render: (_, metric) => (+ <LemonTableLink+ title={metric.display_name || metric.name}+ // Render descriptions with images disabled so a stored image URL can't beacon other viewers.+ description={+ metric.description ? (+ <LemonMarkdown className="max-w-[30rem]" lowKeyHeadings disableImages>+ {metric.description}+ </LemonMarkdown>+ ) : undefined+ }+ />+ ),+ sorter: (a, b) => a.name.localeCompare(b.name),+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, metric) => <StatusTag metric={metric} />,+ },+ {+ title: 'Definition',+ key: 'definition_kind',+ render: (_, metric) => <LemonTag type="option">{humanizeDefinitionKind(metric.definition_kind)}</LemonTag>,+ },+ {+ title: 'Source',+ key: 'created_source',+ render: (_, metric) => <SourceTag metric={metric} />,+ },+ {+ title: 'Owner',+ key: 'owner',+ render: (_, metric) => metric.owner || <span className="text-secondary">Unassigned</span>,+ },+ createdAtColumn<DataCatalogMetricApi>() as LemonTableColumns<DataCatalogMetricApi>[number],+ {+ key: 'actions',+ width: 0,+ render: (_, metric) => {+ const inFlight = !!actionsInFlight[metric.name]+ return (+ <More+ overlay={+ <>+ {metric.status !== 'approved' && (+ <LemonButton+ fullWidth+ loading={inFlight}+ disabledReason={+ metric.is_drifted+ ? 'This metric has drifted from its source insight. Refresh it first.'+ : undefined+ }+ onClick={() => approveMetric(metric.name)}+ >+ Approve+ </LemonButton>+ )}+ {metric.source_insight_short_id && (+ <LemonButton+ fullWidth+ loading={inFlight}+ onClick={() => refreshMetricFromInsight(metric.name)}+ >+ Refresh from insight+ </LemonButton>+ )}+ <LemonButton+ fullWidth+ status="danger"+ disabledReason={inFlight ? 'Working' : undefined}+ onClick={() => confirmDelete(metric)}+ >+ Delete+ </LemonButton>+ </>+ }+ />+ )+ },+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="flex justify-between gap-2 flex-wrap items-center">+ <LemonInput+ type="search"+ placeholder="Search metrics"+ value={filters.search}+ onChange={(search) => setFilters({ search })}+ />+ <div className="flex items-center gap-2 flex-wrap">+ <LemonSegmentedButton+ value={filters.status}+ onChange={(status) => setFilters({ status })}+ options={STATUS_FILTER_OPTIONS}+ size="small"+ />+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ onClick={() => loadMetrics()}+ loading={allMetricsLoading}+ size="small"+ >+ Reload+ </LemonButton>+ </div>+ </div>+ <LemonTable+ data-attr="data-catalog-metrics-table"+ dataSource={metrics}+ rowKey="name"+ columns={columns}+ loading={allMetricsLoading}+ pagination={{ pageSize: 20 }}+ emptyState="No metrics match your filters."+ nouns={['metric', 'metrics']}+ />+ </div>+ )+}diff --git a/products/data_catalog/manifest.tsx b/products/data_catalog/manifest.tsxindex 14a2e6a06350..2eb54f32efb5 100644--- a/products/data_catalog/manifest.tsx+++ b/products/data_catalog/manifest.tsx@@ -1,23 +1,39 @@-/**- * Product manifest for data_catalog.- *- * Defines scenes, routes, URLs, and navigation for this product.- */-import { ProductManifest } from '../../frontend/src/types'+import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'++import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'+import { ProductManifest } from '~/types'export const manifest: ProductManifest = {name: 'DataCatalog',scenes: {- // Define scenes here+ DataCatalog: {+ import: () => import('./frontend/DataCatalogScene'),+ projectBased: true,+ name: 'Data catalog',+ layout: 'app-container',+ iconType: 'data_warehouse',+ description: 'Review and manage governed metrics, certifications, and relationships for your data.',+ },},routes: {- // Define routes here+ '/data-catalog': ['DataCatalog', 'dataCatalog'],},redirects: {},urls: {- // Define URL helpers here+ dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,},fileSystemTypes: {},treeItemsNew: [],- treeItemsProducts: [],+ treeItemsProducts: [+ {+ path: 'Data catalog',+ intents: [ProductKey.DATA_CATALOG],+ category: ProductItemCategory.ANALYTICS,+ iconType: 'data_warehouse',+ href: urls.dataCatalog(),+ flag: FEATURE_FLAGS.PRODUCT_DATA_CATALOG,+ sceneKey: 'DataCatalog',+ },+ ],}diff --git a/products/data_catalog/package.json b/products/data_catalog/package.jsonindex e735d088a970..3af1aec0e1dc 100644--- a/products/data_catalog/package.json+++ b/products/data_catalog/package.json@@ -2,5 +2,21 @@"name": "@posthog/products-data-catalog","scripts": {"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"+ },+ "dependencies": {+ "kea": "catalog:",+ "kea-loaders": "catalog:",+ "kea-router": "catalog:"+ },+ "devDependencies": {+ "@storybook/react": "catalog:"+ },+ "peerDependencies": {+ "@posthog/icons": "catalog:",+ "@types/react": "*",+ "clsx": "*",+ "fast-equals": "catalog:",+ "fuse.js": "*",+ "react": "*"}}