Skip to content

: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.

feat(data-catalog): approve on create from the sql editor and insights (#122768)

Thiago Salvatorebc4507b6dd99
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 700f5091413c..9dcde2395364 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -56,6 +56,7 @@ import { outputPaneLogic } from './outputPaneLogic'
import { QueryHistoryModal } from './QueryHistoryModal'
import { QueryWindow } from './QueryWindow'
import { QuillSQLEditorSceneActions } from './QuillSQLEditorSceneActions'
+import { SaveAsMetricModal } from './SaveAsMetricModal'
import { sqlEditorLogic } from './sqlEditorLogic'
import { SQLEditorMode, isEmbeddedSQLEditorMode } from './sqlEditorModes'
import { useUpdateEditingView } from './useUpdateEditingView'
@@ -377,6 +378,7 @@ export function SQLEditor({
</div>
</BindLogic>
)}
+ <SaveAsMetricModal />
{showFullSceneModals ? (
<>
<MaterializationModal tabId={tabId || ''} />
diff --git a/frontend/src/scenes/data-warehouse/editor/SaveAsMetricModal.tsx b/frontend/src/scenes/data-warehouse/editor/SaveAsMetricModal.tsx
new file mode 100644
index 000000000000..9c7d01c19427
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/editor/SaveAsMetricModal.tsx
@@ -0,0 +1,151 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
+
+import {
+ METRIC_DESCRIPTION_MAX_LENGTH,
+ METRIC_FIELD_COPY,
+ sqlNameFromDisplayName,
+ validateMetricDescription,
+ validateMetricName,
+} from 'products/data_catalog/frontend/common'
+import { MetricNameField } from 'products/data_catalog/frontend/components/MetricNameField'
+import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+
+import { SaveTargetCycler } from './SaveTargetCycler'
+import { SaveAsMetricFields, sqlEditorLogic } from './sqlEditorLogic'
+
+const EMPTY_FIELDS: SaveAsMetricFields = { name: '', display_name: '', description: '', unit: '' }
+
+function trimmedFields(fields: SaveAsMetricFields): SaveAsMetricFields {
+ return {
+ name: fields.name.trim(),
+ display_name: fields.display_name.trim(),
+ description: fields.description.trim(),
+ unit: fields.unit.trim(),
+ }
+}
+
+export function SaveAsMetricModal(): JSX.Element {
+ const { saveAsMetricModal, savingMetricAs } = useValues(sqlEditorLogic)
+ const { closeSaveAsMetricModal, saveAsMetricSubmit } = useActions(sqlEditorLogic)
+ const { allMetrics } = useValues(metricsLogic)
+ const [fields, setFields] = useState<SaveAsMetricFields>(EMPTY_FIELDS)
+ const [query, setQuery] = useState('')
+ const [showErrors, setShowErrors] = useState(false)
+
+ useEffect(() => {
+ if (!saveAsMetricModal) {
+ return
+ }
+ const { prefill, candidates } = saveAsMetricModal
+ const displayName = prefill.display_name ?? ''
+ setFields({
+ ...EMPTY_FIELDS,
+ ...prefill,
+ display_name: displayName,
+ name: prefill.name ?? sqlNameFromDisplayName(displayName),
+ })
+ setQuery(candidates.queries[candidates.initialIndex])
+ setShowErrors(false)
+ }, [saveAsMetricModal])
+
+ const trimmed = trimmedFields(fields)
+ const errors = {
+ display_name: !trimmed.display_name ? 'Name the metric' : undefined,
+ name: trimmed.display_name ? validateMetricName(trimmed.name) : undefined,
+ description: !trimmed.description ? 'Add a description' : validateMetricDescription(trimmed.description),
+ }
+ const selectionProblem = saveAsMetricModal?.selectionProblem ?? undefined
+ const hasErrors = !!(errors.display_name || errors.name || errors.description || selectionProblem)
+ const sqlNameTaken = !!trimmed.name && allMetrics.some((metric) => metric.name === trimmed.name)
+
+ const submit = (approve: boolean): void => {
+ setShowErrors(true)
+ if (!hasErrors) {
+ saveAsMetricSubmit(trimmed, query, false, approve)
+ }
+ }
+
+ return (
+ <LemonModal
+ isOpen={!!saveAsMetricModal}
+ onClose={closeSaveAsMetricModal}
+ title="Save as metric"
+ width={560}
+ footer={
+ <div className="flex flex-wrap justify-end gap-2">
+ <LemonButton
+ type="tertiary"
+ onClick={closeSaveAsMetricModal}
+ disabledReason={savingMetricAs ? 'Saving the metric' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={() => submit(false)}
+ loading={savingMetricAs === 'propose'}
+ disabledReason={savingMetricAs === 'approve' ? 'Saving the metric' : undefined}
+ data-attr="sql-editor-save-metric-proposed"
+ >
+ Save as proposed
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={() => submit(true)}
+ loading={savingMetricAs === 'approve'}
+ disabledReason={savingMetricAs === 'propose' ? 'Saving the metric' : undefined}
+ data-attr="sql-editor-save-metric-approve"
+ >
+ Create and approve
+ </LemonButton>
+ </div>
+ }
+ >
+ {saveAsMetricModal && (
+ <div className="flex flex-col gap-4">
+ <LemonField.Pure error={showErrors ? selectionProblem : undefined}>
+ <SaveTargetCycler
+ candidates={saveAsMetricModal.candidates}
+ onChange={(selectedQuery) => setQuery(selectedQuery)}
+ />
+ </LemonField.Pure>
+ <MetricNameField
+ displayName={fields.display_name}
+ sqlName={fields.name}
+ onChange={(name) => setFields((current) => ({ ...current, ...name }))}
+ displayNameError={showErrors ? errors.display_name : undefined}
+ sqlNameError={showErrors ? errors.name : undefined}
+ sqlNameTaken={sqlNameTaken}
+ autoFocus
+ />
+ <LemonField.Pure
+ label={METRIC_FIELD_COPY.description.label}
+ error={showErrors ? errors.description : undefined}
+ >
+ <LemonTextArea
+ value={fields.description}
+ onChange={(description) => setFields((current) => ({ ...current, description }))}
+ placeholder={METRIC_FIELD_COPY.description.placeholder}
+ maxLength={METRIC_DESCRIPTION_MAX_LENGTH}
+ minRows={2}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Unit (optional)" className="max-w-60">
+ <LemonInput
+ value={fields.unit}
+ onChange={(unit) => setFields((current) => ({ ...current, unit }))}
+ placeholder={METRIC_FIELD_COPY.unit.placeholder}
+ />
+ </LemonField.Pure>
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 360bf89c5604..e5c50a5e296f 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1922,16 +1922,14 @@ describe('sqlEditorLogic', () => {
await expectLogic(logic).toDispatchActions(['createTab']).toMatchValues({ metricPrefill: PREFILL })
})
- it('seeds the dialog with the prefill', async () => {
- const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})
+ it('seeds the save modal with the prefill', async () => {
mountEditor()
logic.actions.setMetricPrefill(PREFILL)
logic.actions.saveAsMetric()
await expectLogic(logic).toFinishAllListeners()
- expect(openForm.mock.calls.at(-1)?.[0].initialValues).toEqual({ saveTarget: 0, ...PREFILL })
- openForm.mockRestore()
+ expect(logic.values.saveAsMetricModal?.prefill).toEqual(PREFILL)
})
it.each([
@@ -1947,12 +1945,17 @@ describe('sqlEditorLogic', () => {
],
])('%s', async (_case, fields, expectedOptionalFields) => {
let createBody: Record<string, any> | undefined
+ let approvals = 0
useMocks({
post: {
'/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {
createBody = (await request.json()) as Record<string, any>
return [200, { name: fields.name }]
},
+ '/api/projects/:team_id/data_catalog/metrics/:name/approve/': () => {
+ approvals += 1
+ return [200, { name: fields.name, status: 'approved' }]
+ },
},
})
mountEditor()
@@ -1969,11 +1972,13 @@ describe('sqlEditorLogic', () => {
})
expect(createBody?.display_name).toEqual(expectedOptionalFields.display_name)
expect(createBody?.unit).toEqual(expectedOptionalFields.unit)
+ expect(approvals).toEqual(1)
expect(logic.values.metricPrefill).toBeNull()
})
- it('asks before it overwrites a taken name, and reopens the form with the typed values and query on dismiss', async () => {
+ it('asks before it overwrites a taken name, and lands the overwrite as proposed', async () => {
const createBodies: Record<string, any>[] = []
+ let approvals = 0
useMocks({
post: {
'/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {
@@ -1991,37 +1996,35 @@ describe('sqlEditorLogic', () => {
},
]
},
+ '/api/projects/:team_id/data_catalog/metrics/:name/approve/': () => {
+ approvals += 1
+ return [200, {}]
+ },
},
})
const open = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})
- const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})
mountEditor()
logic.actions.setQueryInput('SELECT 1;\nSELECT 2;\nSELECT 3')
-
- logic.actions.saveAsMetricSubmit(PREFILL, 'SELECT 2')
+ logic.actions.saveAsMetric()
await expectLogic(logic).toFinishAllListeners()
- expect(createBodies.map((body) => body.overwrite)).toEqual([false])
- // A dismissal runs only onAfterClose.
- open.mock.calls.at(-1)?.[0].onAfterClose?.()
+ logic.actions.saveAsMetricSubmit(PREFILL, 'SELECT 2', false, true)
await expectLogic(logic).toFinishAllListeners()
- const reopenedForm = openForm.mock.calls.at(-1)?.[0]
- expect(reopenedForm?.initialValues).toMatchObject({ ...PREFILL, saveTarget: 1 })
- await reopenedForm?.onSubmit({ ...PREFILL, saveTarget: 1 })
- await expectLogic(logic).toFinishAllListeners()
+ expect(createBodies.map((body) => body.overwrite)).toEqual([false])
+ expect(logic.values.saveAsMetricModal).not.toBeNull()
// A click on Overwrite runs onClick, and the close that follows runs onAfterClose.
const confirmDialog = open.mock.calls.at(-1)?.[0]
confirmDialog?.primaryButton?.onClick?.({} as any)
confirmDialog?.onAfterClose?.()
await expectLogic(logic).toFinishAllListeners()
- expect(createBodies.map((body) => body.overwrite)).toEqual([false, false, true])
- expect(createBodies[2].definition.query).toEqual('SELECT 2')
- expect(openForm).toHaveBeenCalledTimes(1)
+ expect(createBodies.map((body) => body.overwrite)).toEqual([false, true])
+ expect(createBodies[1].definition.query).toEqual('SELECT 2')
+ expect(approvals).toEqual(0)
+ expect(logic.values.saveAsMetricModal).toBeNull()
expect(router.values.location.pathname).toContain(urls.dataCatalogMetric(PREFILL.name))
open.mockRestore()
- openForm.mockRestore()
})
it('refreshes the sidebar metric list after saving a metric', async () => {
@@ -2068,7 +2071,6 @@ describe('sqlEditorLogic', () => {
it.each([
['view', (): void => logic.actions.saveAsView()],
['endpoint', (): void => logic.actions.saveAsEndpoint()],
- ['metric', (): void => logic.actions.saveAsMetric()],
])('refuses to save a selected identifier as a %s', async (_target, openDialog) => {
const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})
logic = sqlEditorLogic({
@@ -2087,6 +2089,20 @@ describe('sqlEditorLogic', () => {
)
openForm.mockRestore()
})
+
+ it('refuses to save a selected identifier as a metric', async () => {
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createEditorWithSelection('weekly_active_users'),
+ })
+ logic.mount()
+
+ logic.actions.saveAsMetric()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.saveAsMetricModal?.selectionProblem).toEqual(SELECTION_NOT_A_QUERY)
+ })
})
describe('Update view', () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 7a9aaf8c958d..fc7be2ad8e1b 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -38,7 +38,6 @@ import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'
@@ -100,13 +99,15 @@ import {
import {
existingMetricFromNameConflict,
- METRIC_FIELD_COPY,
MetricFormPrefill,
- validateMetricDescription,
validateMetricName,
} from 'products/data_catalog/frontend/common'
import {
- dataCatalogMetricsCreate,
+ createMetricAsUser,
+ MetricSaveAction,
+ toastCreatedMetric,
+} from 'products/data_catalog/frontend/createMetricAsUser'
+import {
dataCatalogMetricsPartialUpdate,
dataCatalogMetricsRetrieve,
} from 'products/data_catalog/frontend/generated/api'
@@ -148,7 +149,11 @@ import { IncrementalConfigFields } from './IncrementalConfigFields'
import { findInnermostSelectAtOffset } from './multiQueryUtils'
import { OutputTab, outputPaneLogic } from './outputPaneLogic'
import { findSelectionProblem } from './saveCandidateProblems'
-import { resolveSaveCandidates as resolveSaveCandidatesPure, SaveTargetCycler } from './SaveTargetCycler'
+import {
+ resolveSaveCandidates as resolveSaveCandidatesPure,
+ SaveCandidates,
+ SaveTargetCycler,
+} from './SaveTargetCycler'
import { SQLEditorMode, isEmbeddedSQLEditorMode } from './sqlEditorModes'
import { SQLEditorPlaceholder, placeholderPreviewValues } from './sqlEditorPlaceholders'
import {
@@ -327,6 +332,12 @@ export interface SaveAsMetricFields {
unit: string
}
+export interface SaveAsMetricModalState {
+ candidates: SaveCandidates
+ selectionProblem: string | null
+ prefill: MetricFormPrefill
+}
+
export interface DataWarehouseAccessControlModalProps {
resource:
| AccessControlResourceType.WarehouseTable
@@ -673,6 +684,8 @@ export interface sqlEditorLogicValues {
queryInput: string | null
queryModifiers: HogQLQueryModifiers | null
rejectText: string
+ saveAsMetricModal: SaveAsMetricModalState | null
+ savingMetricAs: MetricSaveAction | null
selectedConnectionId: string | undefined
selectedConnectionSupportsHogQL: boolean
selectedDirectSource: ExternalDataSourceConnectionOptionApi | undefined
@@ -877,6 +890,9 @@ export interface sqlEditorLogicActions {
closeMaterializationModal: () => {
value: true
}
+ closeSaveAsMetricModal: () => {
+ value: true
+ }
createTab: (
query?: string,
view?: DataWarehouseSavedQuery,
@@ -979,6 +995,9 @@ export interface sqlEditorLogicActions {
biEditorState: BIEditorState | null
metricName: string
}
+ openSaveAsMetricModal: (modal: SaveAsMetricModalState) => {
+ modal: SaveAsMetricModalState
+ }
reportAIQueryAccepted: () => {
value: true
}
@@ -1041,8 +1060,10 @@ export interface sqlEditorLogicActions {
saveAsMetricSubmit: (
fields: SaveAsMetricFields,
queryOverride?: string,
- overwrite?: boolean
+ overwrite?: boolean,
+ approve?: boolean
) => {
+ approve: boolean
fields: SaveAsMetricFields
overwrite: boolean
queryOverride: string | undefined
@@ -1170,6 +1191,9 @@ export interface sqlEditorLogicActions {
setQueryModifiers: (queryModifiers: HogQLQueryModifiers | null) => {
queryModifiers: HogQLQueryModifiers | null
}
+ setSavingMetricAs: (savingMetricAs: MetricSaveAction | null) => {
+ savingMetricAs: MetricSaveAction | null
+ }
setSelectedQueryTablesAndColumns: (tablesAndColumns: Record<string, Record<string, boolean>>) => {
tablesAndColumns: Record<string, Record<string, boolean>>
}
@@ -1428,11 +1452,20 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
queryOverride,
}),
saveAsMetric: (queryOverride?: string) => ({ queryOverride }),
- saveAsMetricSubmit: (fields: SaveAsMetricFields, queryOverride?: string, overwrite: boolean = false) => ({
+ saveAsMetricSubmit: (
+ fields: SaveAsMetricFields,
+ queryOverride?: string,
+ overwrite: boolean = false,
+ approve: boolean = true
+ ) => ({
fields,
queryOverride,
overwrite,
+ approve,
}),
+ openSaveAsMetricModal: (modal: SaveAsMetricModalState) => ({ modal }),
+ closeSaveAsMetricModal: true,
+ setSavingMetricAs: (savingMetricAs: MetricSaveAction | null) => ({ savingMetricAs }),
setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => ({ metricPrefill }),
setEditingMetricName: (metricName: string | null) => ({ metricName }),
openMetricFromUrl: (metricName: string, biEditorState: BIEditorState | null) => ({ metricName, biEditorState }),
@@ -1725,6 +1758,19 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setMetricPrefill: (_, { metricPrefill }) => metricPrefill,
},
],
+ saveAsMetricModal: [
+ null as SaveAsMetricModalState | null,
+ {
+ openSaveAsMetricModal: (_, { modal }) => modal,
+ closeSaveAsMetricModal: () => null,
+ },
+ ],
+ savingMetricAs: [
+ null as MetricSaveAction | null,
+ {
+ setSavingMetricAs: (_, { savingMetricAs }) => savingMetricAs,
+ },
+ ],
dashboardId: [
null as number | null,
{
@@ -2996,108 +3042,46 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
// Reopening after a name conflict keeps the statement the user picked, not the cursor default.
const restoredIndex = queryOverride === undefined ? -1 : resolved.queries.indexOf(queryOverride)
const candidates = restoredIndex >= 0 ? { ...resolved, initialIndex: restoredIndex } : resolved
- const selectedRef = { current: candidates.queries[candidates.initialIndex] }
const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)
- LemonDialog.openForm({
- title: 'Save as metric',
- initialValues: {
- saveTarget: candidates.initialIndex,
- name: '',
- display_name: '',
- description: '',
- unit: '',
- ...values.metricPrefill,
- },
- content: (
- <>
- <LemonField name="saveTarget">
- {({ onChange }) => (
- <SaveTargetCycler
- candidates={candidates}
- onChange={(query, index) => {
- selectedRef.current = query
- onChange(index)
- }}
- />
- )}
- </LemonField>
- <LemonField name="name" label={METRIC_FIELD_COPY.name.label}>
- <LemonInput placeholder={METRIC_FIELD_COPY.name.placeholder} autoFocus />
- </LemonField>
- <LemonField
- name="display_name"
- label={METRIC_FIELD_COPY.displayName.label}
- className="mt-2"
- >
- <LemonInput placeholder={METRIC_FIELD_COPY.displayName.placeholder} />
- </LemonField>
- <LemonField name="description" label={METRIC_FIELD_COPY.description.label} className="mt-2">
- {/* stopPropagation keeps Enter from reaching the dialog form and submitting mid-sentence */}
- <LemonTextArea
- placeholder={METRIC_FIELD_COPY.description.placeholder}
- minRows={2}
- stopPropagation
- />
- </LemonField>
- <LemonField name="unit" label={METRIC_FIELD_COPY.unit.label} className="mt-2">
- <LemonInput placeholder={METRIC_FIELD_COPY.unit.placeholder} />
- </LemonField>
- </>
- ),
- errors: {
- saveTarget: () => selectionProblem ?? undefined,
- name: (name) => validateMetricName(name?.trim() || ''),
- description: (description) =>
- !description?.trim() ? 'Add a description' : validateMetricDescription(description.trim()),
- },
- onSubmit: async ({ name, display_name, description, unit }) =>
- actions.saveAsMetricSubmit(
- {
- name: name.trim(),
- display_name: display_name.trim(),
- description: description.trim(),
- unit: unit.trim(),
- },
- selectedRef.current
- ),
- })
+ actions.openSaveAsMetricModal({ candidates, selectionProblem, prefill: values.metricPrefill ?? {} })
},
- saveAsMetricSubmit: async ({ fields, queryOverride, overwrite }) => {
+ saveAsMetricSubmit: async ({ fields, queryOverride, overwrite, approve }) => {
+ if (values.savingMetricAs) {
+ return
+ }
+ actions.setSavingMetricAs(approve ? 'approve' : 'propose')
const biEditorState = getActiveBIEditorState()
try {
// Blank fields are sent as blank, so an overwrite clears the old values.
- const metric = await dataCatalogMetricsCreate(String(ApiConfig.getCurrentTeamId()), {
- name: fields.name,
- display_name: fields.display_name,
- description: fields.description,
- unit: fields.unit,
- created_source: 'user',
- definition: normalizeRawQuerySource({
- ...(values.sourceQuery.source as HogQLQuery),
- query: queryOverride ?? values.queryInput ?? '',
- }) as unknown as Record<string, unknown>,
- overwrite,
- })
+ const created = await createMetricAsUser(
+ {
+ ...fields,
+ definition: normalizeRawQuerySource({
+ ...(values.sourceQuery.source as HogQLQuery),
+ query: queryOverride ?? values.queryInput ?? '',
+ }) as unknown as Record<string, unknown>,
+ overwrite,
+ },
+ approve
+ )
captureBIEditorQuerySaved(biEditorState, 'metric', overwrite ? 'update' : 'create')
metricsLogic.findMounted()?.actions.loadMetrics()
actions.setMetricPrefill(null)
- lemonToast.success(overwrite ? 'Metric overwritten' : 'Metric created')
- router.actions.push(urls.dataCatalogMetric(metric.name))
+ actions.closeSaveAsMetricModal()
+ toastCreatedMetric(created, overwrite)
+ router.actions.push(urls.dataCatalogMetric(created.metric.name))
} catch (error: any) {
const existing = existingMetricFromNameConflict(error)
if (existing) {
openOverwriteMetricDialog({
existing,
- onOverwrite: () => actions.saveAsMetricSubmit(fields, queryOverride, true),
- // The save form closed on submit, so reopen it with the typed values to pick another name.
- onCancel: () => {
- actions.setMetricPrefill(fields)
- actions.saveAsMetric(queryOverride)
- },
+ onOverwrite: () => actions.saveAsMetricSubmit(fields, queryOverride, true, approve),
})
} else {
lemonToast.error(error.detail || 'Failed to create metric')
}
+ } finally {
+ actions.setSavingMetricAs(null)
}
},
openMetricFromUrl: async ({ metricName, biEditorState }, breakpoint) => {
diff --git a/products/data_catalog/frontend/components/MetricFromInsightModal.tsx b/products/data_catalog/frontend/components/MetricFromInsightModal.tsx
index 5468e3442db5..d8a72de27bda 100644
--- a/products/data_catalog/frontend/components/MetricFromInsightModal.tsx
+++ b/products/data_catalog/frontend/components/MetricFromInsightModal.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useMemo, useState } from 'react'
+import { useEffect, useState } from 'react'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
@@ -7,34 +7,47 @@ import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
import { Link } from 'lib/lemon-ui/Link'
-import { slugify } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
-import { validateMetricDescription, validateMetricName } from '../common'
+import { METRIC_FIELD_COPY, sqlNameFromDisplayName, validateMetricDescription, validateMetricName } from '../common'
import { metricsLogic } from '../metricsLogic'
+import { MetricNameField, MetricNameValue } from './MetricNameField'
export interface MetricFromInsightModalProps {
insightShortId?: string
insightName?: string
}
+function namesFromInsight(insightName: string | undefined): MetricNameValue {
+ const displayName = insightName ?? ''
+ return { display_name: displayName, name: sqlNameFromDisplayName(displayName) }
+}
+
export function MetricFromInsightModal({ insightShortId, insightName }: MetricFromInsightModalProps): JSX.Element {
- const { metricFromInsightModalOpen, isCreatingMetric, allMetrics } = useValues(metricsLogic)
+ const { metricFromInsightModalOpen, creatingMetricAs, allMetrics } = useValues(metricsLogic)
const { createMetricFromInsight, closeMetricFromInsightModal } = useActions(metricsLogic)
- const [name, setName] = useState('')
- const [displayName, setDisplayName] = useState('')
+ const [names, setNames] = useState<MetricNameValue>(() => namesFromInsight(insightName))
const [description, setDescription] = useState('')
+ const [unit, setUnit] = useState('')
- const prefilledName = useMemo(() => slugify(insightName || '').replace(/-/g, '_'), [insightName])
- const effectiveName = name || prefilledName
- const nameError = validateMetricName(effectiveName)
+ useEffect(() => {
+ if (metricFromInsightModalOpen) {
+ setNames(namesFromInsight(insightName))
+ setDescription('')
+ setUnit('')
+ }
+ }, [metricFromInsightModalOpen, insightName])
+
+ const sqlName = names.name.trim()
+ const nameError = names.display_name.trim() ? validateMetricName(sqlName) : 'Name the metric'
+ const descriptionError = validateMetricDescription(description)
+ const sqlNameTaken = !!sqlName && allMetrics.some((metric) => metric.name === sqlName)
const metricsFromThisInsight = insightShortId
? allMetrics.filter((metric) => metric.source_insight_short_id === insightShortId)
: []
- const descriptionError = validateMetricDescription(description)
const submitDisabledReason = !insightShortId
? 'Save the insight first'
: nameError
@@ -42,32 +55,27 @@ export function MetricFromInsightModal({ insightShortId, insightName }: MetricFr
: !description.trim()
? 'Add a description'
: descriptionError
- ? descriptionError
- : undefined
-
- const handleClose = (): void => {
- setName('')
- setDisplayName('')
- setDescription('')
- closeMetricFromInsightModal()
- }
- const handleSubmit = (): void => {
+ const submit = (approve: boolean): void => {
if (submitDisabledReason || !insightShortId) {
return
}
- createMetricFromInsight({
- name: effectiveName,
- display_name: displayName.trim(),
- description: description.trim(),
- source_insight_short_id: insightShortId,
- })
+ createMetricFromInsight(
+ {
+ name: sqlName,
+ display_name: names.display_name.trim(),
+ description: description.trim(),
+ unit: unit.trim(),
+ source_insight_short_id: insightShortId,
+ },
+ approve
+ )
}
return (
<LemonModal
isOpen={metricFromInsightModalOpen}
- onClose={handleClose}
+ onClose={closeMetricFromInsightModal}
width={560}
title="Create metric from insight"
>
@@ -95,49 +103,58 @@ export function MetricFromInsightModal({ insightShortId, insightName }: MetricFr
</div>
)}
- <LemonField.Pure
- label="Name"
- error={effectiveName ? nameError : undefined}
- info="A unique identifier for the metric, like monthly_active_users."
- >
- <LemonInput
- value={effectiveName}
- onChange={setName}
- placeholder="monthly_active_users"
- autoFocus
- />
- </LemonField.Pure>
-
- <LemonField.Pure label="Display name">
- <LemonInput value={displayName} onChange={setDisplayName} placeholder="Monthly active users" />
- </LemonField.Pure>
+ <MetricNameField
+ displayName={names.display_name}
+ sqlName={names.name}
+ onChange={setNames}
+ sqlNameError={names.display_name.trim() ? validateMetricName(sqlName) : undefined}
+ sqlNameTaken={sqlNameTaken}
+ autoFocus
+ />
<LemonField.Pure
- label="Description"
+ label={METRIC_FIELD_COPY.description.label}
error={descriptionError}
info="One or two short sentences: what the number is and what it counts."
>
<LemonInput
value={description}
onChange={setDescription}
- placeholder="What this metric measures and how to read it"
+ placeholder={METRIC_FIELD_COPY.description.placeholder}
/>
</LemonField.Pure>
+
+ <LemonField.Pure label="Unit (optional)" className="max-w-60">
+ <LemonInput value={unit} onChange={setUnit} placeholder={METRIC_FIELD_COPY.unit.placeholder} />
+ </LemonField.Pure>
</div>
</LemonModal.Content>
<LemonModal.Footer>
- <LemonButton type="secondary" onClick={handleClose} disabled={isCreatingMetric}>
+ <LemonButton type="tertiary" onClick={closeMetricFromInsightModal} disabled={!!creatingMetricAs}>
Cancel
</LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={() => submit(false)}
+ loading={creatingMetricAs === 'propose'}
+ disabledReason={
+ submitDisabledReason ?? (creatingMetricAs === 'approve' ? 'Saving the metric' : undefined)
+ }
+ data-attr="data-catalog-create-metric-from-insight-proposed"
+ >
+ Save as proposed
+ </LemonButton>
<LemonButton
type="primary"
- onClick={handleSubmit}
- loading={isCreatingMetric}
- disabledReason={submitDisabledReason}
+ onClick={() => submit(true)}
+ loading={creatingMetricAs === 'approve'}
+ disabledReason={
+ submitDisabledReason ?? (creatingMetricAs === 'propose' ? 'Saving the metric' : undefined)
+ }
data-attr="data-catalog-create-metric-from-insight-submit"
>
- Create metric
+ Create and approve
</LemonButton>
</LemonModal.Footer>
</LemonModal>
diff --git a/products/data_catalog/frontend/createMetricAsUser.ts b/products/data_catalog/frontend/createMetricAsUser.ts
index a68aab19487d..cfceeb9bcc6e 100644
--- a/products/data_catalog/frontend/createMetricAsUser.ts
+++ b/products/data_catalog/frontend/createMetricAsUser.ts
@@ -1,10 +1,18 @@
import { ApiConfig } from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { dataCatalogMetricsApproveCreate, dataCatalogMetricsCreate } from './generated/api'
import type { DataCatalogMetricApi } from './generated/api.schemas'
export type MetricCreateRequest = Omit<Parameters<typeof dataCatalogMetricsCreate>[1], 'created_source'>
+export interface ToastButton {
+ label: string
+ action: () => void
+}
+
+export type MetricSaveAction = 'approve' | 'propose'
+
export type CreatedMetricApproval = 'approved' | 'proposed' | 'approval_failed'
export interface CreatedMetric {
@@ -27,3 +35,16 @@ export async function createMetricAsUser(request: MetricCreateRequest, approve:
return { metric, approval: 'approval_failed' }
}
}
+
+export function toastCreatedMetric(created: CreatedMetric, overwrite: boolean, button?: ToastButton): void {
+ const options = button ? { button } : undefined
+ if (overwrite) {
+ lemonToast.success('Metric overwritten. It needs approval.', options)
+ } else if (created.approval === 'approved') {
+ lemonToast.success('Metric created and approved', options)
+ } else if (created.approval === 'approval_failed') {
+ lemonToast.warning('Metric created, but approving it failed. Approve it from the banner.', options)
+ } else {
+ lemonToast.success('Metric saved as proposed', options)
+ }
+}
diff --git a/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.test.ts b/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.test.ts
index 55ca95f76a95..3fe7a4f28ff2 100644
--- a/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.test.ts
+++ b/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.test.ts
@@ -122,7 +122,7 @@ describe('dataCatalogNewMetricSceneLogic', () => {
expect((dataCatalogMetricsApproveCreate as jest.Mock).mock.calls).toEqual(
Array(approveCalls).fill(['1', 'monthly_active_users', { expected_updated_at: CREATED_AT }])
)
- expect(lemonToast.success).toHaveBeenCalledWith(toast)
+ expect((lemonToast.success as jest.Mock).mock.calls.at(-1)?.[0]).toEqual(toast)
expect(router.values.location.pathname).toContain(urls.dataCatalogMetric('monthly_active_users'))
})
@@ -148,7 +148,9 @@ describe('dataCatalogNewMetricSceneLogic', () => {
expect((dataCatalogMetricsCreate as jest.Mock).mock.calls[1][1].overwrite).toBe(true)
expect(dataCatalogMetricsApproveCreate).not.toHaveBeenCalled()
- expect(lemonToast.success).toHaveBeenCalledWith('Metric overwritten. It needs approval.')
+ expect((lemonToast.success as jest.Mock).mock.calls.at(-1)?.[0]).toEqual(
+ 'Metric overwritten. It needs approval.'
+ )
})
it('still opens the created metric when approving it fails', async () => {
@@ -158,7 +160,7 @@ describe('dataCatalogNewMetricSceneLogic', () => {
logic.actions.submitMetric(true)
await expectLogic(logic).toFinishAllListeners()
- expect(lemonToast.warning).toHaveBeenCalledWith(
+ expect((lemonToast.warning as jest.Mock).mock.calls.at(-1)?.[0]).toEqual(
'Metric created, but approving it failed. Approve it from the banner.'
)
expect(router.values.location.pathname).toContain(urls.dataCatalogMetric('monthly_active_users'))
diff --git a/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.ts b/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.ts
index 0d607b76e648..d6599404c9e0 100644
--- a/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.ts
+++ b/products/data_catalog/frontend/dataCatalogNewMetricSceneLogic.ts
@@ -22,15 +22,13 @@ import {
validateMetricDescription,
validateMetricName,
} from './common'
-import { CreatedMetric, createMetricAsUser, MetricCreateRequest } from './createMetricAsUser'
+import { createMetricAsUser, MetricCreateRequest, MetricSaveAction, toastCreatedMetric } from './createMetricAsUser'
import type { DataCatalogMetricApi } from './generated/api.schemas'
import { metricsLogic } from './metricsLogic'
import { openOverwriteMetricDialog } from './openOverwriteMetricDialog'
export type MetricDefinitionType = 'sql' | 'insight' | 'markdown'
-export type MetricSaveAction = 'approve' | 'propose'
-
export interface NewMetricFormValues {
display_name: string
name: string
@@ -104,18 +102,6 @@ function definitionError(form: NewMetricFormValues): string | undefined {
: undefined
}
-function savedToast(created: CreatedMetric, overwrite: boolean): void {
- if (overwrite) {
- lemonToast.success('Metric overwritten. It needs approval.')
- } else if (created.approval === 'approved') {
- lemonToast.success('Metric created and approved')
- } else if (created.approval === 'approval_failed') {
- lemonToast.warning('Metric created, but approving it failed. Approve it from the banner.')
- } else {
- lemonToast.success('Metric saved as proposed')
- }
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataCatalogNewMetricSceneLogicValues {
allMetrics: DataCatalogMetricApi[] // metricsLogic
@@ -527,7 +513,7 @@ export const dataCatalogNewMetricSceneLogic = kea<dataCatalogNewMetricSceneLogic
created.metric,
...values.allMetrics.filter((metric) => metric.name !== created.metric.name),
])
- savedToast(created, overwrite)
+ toastCreatedMetric(created, overwrite)
actions.setLeaving()
router.actions.push(urls.dataCatalogMetric(created.metric.name))
} catch (error) {
diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.ts
index 02d6a2022ad8..c84925f3f7ed 100644
--- a/products/data_catalog/frontend/metricsLogic.test.ts
+++ b/products/data_catalog/frontend/metricsLogic.test.ts
@@ -126,12 +126,16 @@ describe('metricsLogic', () => {
.mockResolvedValueOnce(overwritten)
logic.actions.openMetricFromInsightModal()
- logic.actions.createMetricFromInsight({
- name: 'weekly_active_users',
- display_name: '',
- description: 'Weekly active users',
- source_insight_short_id: 'abc123',
- })
+ logic.actions.createMetricFromInsight(
+ {
+ name: 'weekly_active_users',
+ display_name: '',
+ description: 'Weekly active users',
+ unit: '',
+ source_insight_short_id: 'abc123',
+ },
+ true
+ )
await expectLogic(logic).toFinishAllListeners()
expect((dataCatalogMetricsCreate as jest.Mock).mock.calls[0][1].overwrite).toBe(false)
@@ -334,12 +338,16 @@ describe('metricsLogic', () => {
)
logic.actions.openMetricFromInsightModal()
- logic.actions.createMetricFromInsight({
- name: 'from_insight',
- display_name: '',
- description: 'Snapshotted from an insight',
- source_insight_short_id: 'abc123',
- })
+ logic.actions.createMetricFromInsight(
+ {
+ name: 'from_insight',
+ display_name: '',
+ description: 'Snapshotted from an insight',
+ unit: '',
+ source_insight_short_id: 'abc123',
+ },
+ false
+ )
await expectLogic(logic).toFinishAllListeners()
const body = (dataCatalogMetricsCreate as jest.Mock).mock.calls.at(-1)?.[1]
diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsx
index 14b45946607f..bd64af3454ec 100644
--- a/products/data_catalog/frontend/metricsLogic.tsx
+++ b/products/data_catalog/frontend/metricsLogic.tsx
@@ -12,11 +12,11 @@ import { userLogic } from 'scenes/userLogic'
import { UserType } from '~/types'
import { existingMetricFromNameConflict, metricCount } from './common'
+import { createMetricAsUser, MetricSaveAction, toastCreatedMetric } from './createMetricAsUser'
import {
dataCatalogMetricsApproveCreate,
dataCatalogMetricsBulkApproveCreate,
dataCatalogMetricsBulkDeleteCreate,
- dataCatalogMetricsCreate,
dataCatalogMetricsDestroy,
dataCatalogMetricsList,
dataCatalogMetricsRefreshFromInsightCreate,
@@ -46,6 +46,7 @@ export interface MetricFromInsightRequest {
name: string
display_name: string
description: string
+ unit: string
source_insight_short_id: string
}
@@ -78,8 +79,8 @@ export interface metricsLogicValues {
allMetrics: DataCatalogMetricApi[]
allMetricsLoading: boolean
bulkActionInFlight: BulkMetricAction | null
+ creatingMetricAs: MetricSaveAction | null
filters: MetricsFilters
- isCreatingMetric: boolean
metricFromInsightModalOpen: boolean
metrics: DataCatalogMetricApi[]
proposedCount: number
@@ -109,8 +110,10 @@ export interface metricsLogicActions {
}
createMetricFromInsight: (
request: MetricFromInsightRequest,
+ approve: boolean,
overwrite?: boolean
) => {
+ approve: boolean
overwrite: boolean
request: MetricFromInsightRequest
}
@@ -148,8 +151,8 @@ export interface metricsLogicActions {
setBulkActionInFlight: (bulkAction: BulkMetricAction | null) => {
bulkAction: BulkMetricAction | null
}
- setCreatingMetric: (creating: boolean) => {
- creating: boolean
+ setCreatingMetricAs: (creatingAs: MetricSaveAction | null) => {
+ creatingAs: MetricSaveAction | null
}
setFilters: (filters: Partial<MetricsFilters>) => {
filters: Partial<MetricsFilters>
@@ -178,7 +181,7 @@ export const metricsLogic = kea<metricsLogicType>([
})),
actions({
setFilters: (filters: Partial<MetricsFilters>) => ({ filters }),
- setCreatingMetric: (creating: boolean) => ({ creating }),
+ setCreatingMetricAs: (creatingAs: MetricSaveAction | null) => ({ creatingAs }),
approveMetric: (name: string) => ({ name }),
refreshMetricFromInsight: (name: string) => ({ name }),
deleteMetric: (name: string) => ({ name }),
@@ -188,8 +191,9 @@ export const metricsLogic = kea<metricsLogicType>([
setBulkActionInFlight: (bulkAction: BulkMetricAction | null) => ({ bulkAction }),
openMetricFromInsightModal: true,
closeMetricFromInsightModal: true,
- createMetricFromInsight: (request: MetricFromInsightRequest, overwrite: boolean = false) => ({
+ createMetricFromInsight: (request: MetricFromInsightRequest, approve: boolean, overwrite: boolean = false) => ({
request,
+ approve,
overwrite,
}),
}),
@@ -222,10 +226,10 @@ export const metricsLogic = kea<metricsLogicType>([
setFilters: (state, { filters }) => ({ ...state, ...filters }),
},
],
- isCreatingMetric: [
- false,
+ creatingMetricAs: [
+ null as MetricSaveAction | null,
{
- setCreatingMetric: (_, { creating }) => creating,
+ setCreatingMetricAs: (_, { creatingAs }) => creatingAs,
},
],
metricFromInsightModalOpen: [
@@ -289,34 +293,25 @@ export const metricsLogic = kea<metricsLogicType>([
result_count: values.metrics.length,
})
},
- createMetricFromInsight: async ({ request, overwrite }) => {
- if (values.isCreatingMetric) {
+ createMetricFromInsight: async ({ request, approve, overwrite }) => {
+ if (values.creatingMetricAs) {
return
}
- actions.setCreatingMetric(true)
+ actions.setCreatingMetricAs(approve ? 'approve' : 'propose')
try {
- const created = await dataCatalogMetricsCreate(projectId(), {
- name: request.name,
- display_name: request.display_name,
- description: request.description,
- source_insight_short_id: request.source_insight_short_id,
- created_source: 'user',
- overwrite,
- })
- actions.loadMetricsSuccess(withCreatedMetric(values.allMetrics, created))
+ const created = await createMetricAsUser({ ...request, overwrite }, approve)
+ actions.loadMetricsSuccess(withCreatedMetric(values.allMetrics, created.metric))
actions.closeMetricFromInsightModal()
- lemonToast.success(overwrite ? 'Metric overwritten from insight' : 'Metric created from insight', {
- button: {
- label: 'View metric',
- action: () => router.actions.push(urls.dataCatalogMetric(created.name)),
- },
+ toastCreatedMetric(created, overwrite, {
+ label: 'View metric',
+ action: () => router.actions.push(urls.dataCatalogMetric(created.metric.name)),
})
} catch (error) {
const existing = existingMetricFromNameConflict(error)
if (existing) {
openOverwriteMetricDialog({
existing,
- onOverwrite: () => actions.createMetricFromInsight(request, true),
+ onOverwrite: () => actions.createMetricFromInsight(request, approve, true),
})
} else {
lemonToast.error(
@@ -324,7 +319,7 @@ export const metricsLogic = kea<metricsLogicType>([
)
}
} finally {
- actions.setCreatingMetric(false)
+ actions.setCreatingMetricAs(null)
}
},
approveMetric: async ({ name }) => {