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.

fix(data-catalog): ask before overwriting a metric with a taken name (#118042)

Sinan Kucukkoseler2ba93d238a8c
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 95231567599c..29f5070b706c 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1929,9 +1929,9 @@ describe('sqlEditorLogic', () => {
{ display_name: 'Monthly active users', unit: 'users' },
],
[
- 'omits the optional fields when they are blank',
+ 'posts blank optional fields as blank, so an overwrite clears them',
{ ...PREFILL, display_name: '', unit: '' },
- { display_name: undefined, unit: undefined },
+ { display_name: '', unit: '' },
],
])('%s', async (_case, fields, expectedOptionalFields) => {
let createBody: Record<string, any> | undefined
@@ -1950,12 +1950,68 @@ describe('sqlEditorLogic', () => {
logic.actions.saveAsMetricSubmit(fields)
await expectLogic(logic).toFinishAllListeners()
- expect(createBody).toMatchObject({ name: fields.name, description: fields.description })
+ expect(createBody).toMatchObject({
+ name: fields.name,
+ description: fields.description,
+ created_source: 'user',
+ })
expect(createBody?.display_name).toEqual(expectedOptionalFields.display_name)
expect(createBody?.unit).toEqual(expectedOptionalFields.unit)
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 () => {
+ const createBodies: Record<string, any>[] = []
+ useMocks({
+ post: {
+ '/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ createBodies.push(body)
+ return body.overwrite
+ ? [201, { name: body.name }]
+ : [
+ 409,
+ {
+ type: 'invalid_request',
+ code: 'metric_name_taken',
+ detail: 'A metric with this name already exists.',
+ extra: { existing_metric: { name: body.name, status: 'approved' } },
+ },
+ ]
+ },
+ },
+ })
+ 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')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createBodies.map((body) => body.overwrite)).toEqual([false])
+ // A dismissal runs only onAfterClose.
+ open.mock.calls.at(-1)?.[0].onAfterClose?.()
+ 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()
+ // 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(router.values.location.pathname).toContain(urls.dataCatalogMetric(PREFILL.name))
+ open.mockRestore()
+ openForm.mockRestore()
+ })
+
it('refreshes the sidebar metric list after saving a metric', async () => {
const savedMetrics: Record<string, any>[] = []
useMocks({
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 2a9e8c6e972c..ecbad9c02f40 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -99,6 +99,7 @@ import {
} from '~/types'
import {
+ existingMetricFromNameConflict,
METRIC_FIELD_COPY,
MetricFormPrefill,
validateMetricDescription,
@@ -110,6 +111,7 @@ import {
dataCatalogMetricsRetrieve,
} from 'products/data_catalog/frontend/generated/api'
import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
+import { openOverwriteMetricDialog } from 'products/data_catalog/frontend/openOverwriteMetricDialog'
import { warehouseSavedQueriesRetrieve } from 'products/data_warehouse/frontend/generated/api'
import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'
import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
@@ -1030,14 +1032,16 @@ export interface sqlEditorLogicActions {
name: string
queryOverride: string | undefined
}
- saveAsMetric: () => {
- value: true
+ saveAsMetric: (queryOverride?: string) => {
+ queryOverride: string | undefined
}
saveAsMetricSubmit: (
fields: SaveAsMetricFields,
- queryOverride?: string
+ queryOverride?: string,
+ overwrite?: boolean
) => {
fields: SaveAsMetricFields
+ overwrite: boolean
queryOverride: string | undefined
}
saveAsView: (
@@ -1420,10 +1424,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
description,
queryOverride,
}),
- saveAsMetric: true,
- saveAsMetricSubmit: (fields: SaveAsMetricFields, queryOverride?: string) => ({
+ saveAsMetric: (queryOverride?: string) => ({ queryOverride }),
+ saveAsMetricSubmit: (fields: SaveAsMetricFields, queryOverride?: string, overwrite: boolean = false) => ({
fields,
queryOverride,
+ overwrite,
}),
setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => ({ metricPrefill }),
setEditingMetricName: (metricName: string | null) => ({ metricName }),
@@ -2982,8 +2987,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
lemonToast.error(error.detail || 'Failed to create endpoint')
}
},
- saveAsMetric: async () => {
- const candidates = resolveSaveCandidates()
+ saveAsMetric: async ({ queryOverride }) => {
+ const resolved = resolveSaveCandidates()
+ // 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({
@@ -3050,26 +3058,42 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
),
})
},
- saveAsMetricSubmit: async ({ fields, queryOverride }) => {
+ saveAsMetricSubmit: async ({ fields, queryOverride, overwrite }) => {
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 || undefined,
+ display_name: fields.display_name,
description: fields.description,
- unit: fields.unit || undefined,
+ unit: fields.unit,
+ created_source: 'user',
definition: normalizeRawQuerySource({
...(values.sourceQuery.source as HogQLQuery),
query: queryOverride ?? values.queryInput ?? '',
}) as unknown as Record<string, unknown>,
+ overwrite,
})
- captureBIEditorQuerySaved(biEditorState, 'metric', 'create')
+ captureBIEditorQuerySaved(biEditorState, 'metric', overwrite ? 'update' : 'create')
metricsLogic.findMounted()?.actions.loadMetrics()
actions.setMetricPrefill(null)
- lemonToast.success('Metric created')
+ lemonToast.success(overwrite ? 'Metric overwritten' : 'Metric created')
router.actions.push(urls.dataCatalogMetric(metric.name))
} catch (error: any) {
- lemonToast.error(error.detail || 'Failed to create metric')
+ 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)
+ },
+ })
+ } else {
+ lemonToast.error(error.detail || 'Failed to create metric')
+ }
}
},
openMetricFromUrl: async ({ metricName, biEditorState }, breakpoint) => {
diff --git a/products/data_catalog/frontend/common.ts b/products/data_catalog/frontend/common.ts
index b89fc0bd5bd1..881a22ab29a3 100644
--- a/products/data_catalog/frontend/common.ts
+++ b/products/data_catalog/frontend/common.ts
@@ -2,6 +2,13 @@ import posthog from 'posthog-js'
import type { Sorting } from '@posthog/lemon-ui'
+import { ApiError } from 'lib/api'
+
+import type {
+ DataCatalogMetricNameConflictApi,
+ DataCatalogMetricNameConflictExistingApi,
+} from './generated/api.schemas'
+
export const METRIC_NAME_REGEX = /^[A-Za-z][A-Za-z0-9_]*$/
export const HOGQL_METRIC_DEFINITION_KIND = 'HogQLQuery'
@@ -77,3 +84,12 @@ export function validateMetricDescription(description: string): string | undefin
}
return undefined
}
+
+/** The metric that blocked a create because it holds the same name, or null for any other error. */
+export function existingMetricFromNameConflict(error: unknown): DataCatalogMetricNameConflictExistingApi | null {
+ if (!(error instanceof ApiError) || error.status !== 409 || error.code !== 'metric_name_taken') {
+ return null
+ }
+ const body = error.data as DataCatalogMetricNameConflictApi | undefined
+ return body?.extra?.existing_metric ?? null
+}
diff --git a/products/data_catalog/frontend/components/NewMetricModal.tsx b/products/data_catalog/frontend/components/NewMetricModal.tsx
index 63de01640aa2..c724692c048f 100644
--- a/products/data_catalog/frontend/components/NewMetricModal.tsx
+++ b/products/data_catalog/frontend/components/NewMetricModal.tsx
@@ -148,7 +148,7 @@ export function NewMetricModal(): JSX.Element {
</LemonButton>
<LemonButton
type="primary"
- onClick={createMetric}
+ onClick={() => createMetric()}
loading={isCreatingMetric}
disabledReason={submitDisabledReason}
data-attr="data-catalog-create-metric-submit"
diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.ts
index 138af4f5024e..73c9ab2ee64a 100644
--- a/products/data_catalog/frontend/metricsLogic.test.ts
+++ b/products/data_catalog/frontend/metricsLogic.test.ts
@@ -19,15 +19,25 @@ import {
} from './generated/api'
import type { DataCatalogMetricApi } from './generated/api.schemas'
import { metricsLogic } from './metricsLogic'
+import { openOverwriteMetricDialog } from './openOverwriteMetricDialog'
jest.mock('lib/api', () => {
class ApiError extends Error {
status?: number
detail: string | null
- constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {
+ code: string | null
+ data?: Record<string, any>
+ constructor(
+ message?: string,
+ status?: number,
+ _headers?: unknown,
+ data?: { detail?: string; code?: string } & Record<string, any>
+ ) {
super(message)
this.status = status
this.detail = data?.detail ?? null
+ this.code = data?.code ?? null
+ this.data = data
}
}
return {
@@ -42,6 +52,8 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },
}))
+jest.mock('./openOverwriteMetricDialog', () => ({ openOverwriteMetricDialog: jest.fn() }))
+
jest.mock('./generated/api', () => ({
dataCatalogMetricsList: jest.fn(),
dataCatalogMetricsCreate: jest.fn(),
@@ -131,6 +143,67 @@ describe('metricsLogic', () => {
expect(logic.values.allMetrics.map((metric) => metric.name)).toContain('monthly_active_users')
})
+ it.each([
+ [
+ 'the new metric modal',
+ 'newMetricModalOpen',
+ (built: typeof logic): void => {
+ built.actions.openNewMetricModal()
+ built.actions.setNewMetricForm({
+ name: 'weekly_active_users',
+ description: 'Weekly active users',
+ definitionType: 'insight',
+ sourceInsightShortId: 'abc123',
+ })
+ built.actions.createMetric()
+ },
+ ],
+ [
+ 'the insight modal',
+ 'metricFromInsightModalOpen',
+ (built: typeof logic): void => {
+ built.actions.openMetricFromInsightModal()
+ built.actions.createMetricFromInsight({
+ name: 'weekly_active_users',
+ display_name: '',
+ description: 'Weekly active users',
+ source_insight_short_id: 'abc123',
+ })
+ },
+ ],
+ ] as const)('asks before it overwrites a taken name from %s', async (_source, modalOpenKey, submit) => {
+ const overwritten = buildMetric({ description: 'Overwritten' })
+ ;(dataCatalogMetricsCreate as jest.Mock)
+ .mockRejectedValueOnce(
+ new ApiError('taken', 409, undefined, {
+ code: 'metric_name_taken',
+ extra: { existing_metric: { name: 'weekly_active_users', status: 'approved' } },
+ })
+ )
+ .mockResolvedValueOnce(overwritten)
+
+ submit(logic)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setNewMetricForm({ name: 'edited_after_submit' })
+
+ expect((dataCatalogMetricsCreate as jest.Mock).mock.calls[0][1].overwrite).toBe(false)
+ expect(lemonToast.error).not.toHaveBeenCalled()
+ expect(logic.values[modalOpenKey]).toEqual(true)
+ const { existing, onOverwrite } = (openOverwriteMetricDialog as jest.Mock).mock.calls[0][0]
+ expect(existing).toEqual({ name: 'weekly_active_users', status: 'approved' })
+
+ onOverwrite()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect((dataCatalogMetricsCreate as jest.Mock).mock.calls[1][1]).toMatchObject({
+ name: 'weekly_active_users',
+ created_source: 'user',
+ overwrite: true,
+ })
+ expect(logic.values[modalOpenKey]).toEqual(false)
+ expect(logic.values.allMetrics).toEqual([overwritten])
+ })
+
it('creates a markdown metric as a stub and routes to the metric page to author it', async () => {
;(dataCatalogMetricsCreate as jest.Mock).mockResolvedValue(
buildMetric({ id: 'metric-4', name: 'mrr', definition_kind: null })
@@ -146,7 +219,7 @@ describe('metricsLogic', () => {
await expectLogic(logic).toFinishAllListeners()
const body = (dataCatalogMetricsCreate as jest.Mock).mock.calls.at(-1)?.[1]
- expect(body.definition).toBeUndefined()
+ expect(body.definition).toBeNull()
expect(router.values.location.pathname).toContain(urls.dataCatalogMetric('mrr'))
expect(router.values.searchParams.edit).toEqual('definition')
})
diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsx
index e67a6a00f31d..26710b2adba4 100644
--- a/products/data_catalog/frontend/metricsLogic.tsx
+++ b/products/data_catalog/frontend/metricsLogic.tsx
@@ -11,7 +11,7 @@ import { userLogic } from 'scenes/userLogic'
import { UserType } from '~/types'
-import { metricCount } from './common'
+import { existingMetricFromNameConflict, metricCount } from './common'
import {
dataCatalogMetricsApproveCreate,
dataCatalogMetricsBulkApproveCreate,
@@ -22,6 +22,7 @@ import {
dataCatalogMetricsRefreshFromInsightCreate,
} from './generated/api'
import type { DataCatalogMetricApi, DataCatalogMetricBulkSkipApi } from './generated/api.schemas'
+import { openOverwriteMetricDialog } from './openOverwriteMetricDialog'
export type MetricStatusFilter = 'all' | 'proposed' | 'approved'
@@ -81,6 +82,11 @@ function apiErrorDetail(error: unknown): string | null {
return error instanceof ApiError ? error.detail : null
}
+/** Puts a created metric first, replacing the row it overwrote. */
+function withCreatedMetric(metrics: DataCatalogMetricApi[], created: DataCatalogMetricApi): DataCatalogMetricApi[] {
+ return [created, ...metrics.filter((metric) => metric.name !== created.name)]
+}
+
function skippedMessage(skipped: DataCatalogMetricBulkSkipApi[]): string {
const countByReason = new Map<string, number>()
for (const skip of skipped) {
@@ -134,10 +140,18 @@ export interface metricsLogicActions {
closeNewMetricModal: () => {
value: true
}
- createMetric: () => {
- value: true
+ createMetric: (
+ overwrite?: boolean,
+ form?: NewMetricForm
+ ) => {
+ form: NewMetricForm | undefined
+ overwrite: boolean
}
- createMetricFromInsight: (request: MetricFromInsightRequest) => {
+ createMetricFromInsight: (
+ request: MetricFromInsightRequest,
+ overwrite?: boolean
+ ) => {
+ overwrite: boolean
request: MetricFromInsightRequest
}
deleteMetric: (name: string) => {
@@ -249,7 +263,8 @@ export const metricsLogic = kea<metricsLogicType>([
setNewMetricForm: (form: Partial<NewMetricForm>) => ({ form }),
setInsightSearch: (search: string) => ({ search }),
loadSavedInsights: true,
- createMetric: true,
+ // `form` is the submitted snapshot on an overwrite retry, so an edit made while the first request ran is not saved.
+ createMetric: (overwrite: boolean = false, form?: NewMetricForm) => ({ overwrite, form }),
setCreatingMetric: (creating: boolean) => ({ creating }),
approveMetric: (name: string) => ({ name }),
refreshMetricFromInsight: (name: string) => ({ name }),
@@ -260,7 +275,10 @@ export const metricsLogic = kea<metricsLogicType>([
setBulkActionInFlight: (bulkAction: BulkMetricAction | null) => ({ bulkAction }),
openMetricFromInsightModal: true,
closeMetricFromInsightModal: true,
- createMetricFromInsight: (request: MetricFromInsightRequest) => ({ request }),
+ createMetricFromInsight: (request: MetricFromInsightRequest, overwrite: boolean = false) => ({
+ request,
+ overwrite,
+ }),
}),
lazyLoaders(() => ({
allMetrics: [
@@ -414,11 +432,11 @@ export const metricsLogic = kea<metricsLogicType>([
urls.sqlEditor({ source: 'metric', metricPrefill: { name, display_name, description, unit } })
)
},
- createMetric: async () => {
+ createMetric: async ({ overwrite, form: submittedForm }) => {
if (values.isCreatingMetric) {
return
}
- const form = values.newMetricForm
+ const form = submittedForm ?? values.newMetricForm
if (form.definitionType === 'sql') {
lemonToast.error('Create SQL metrics from the SQL editor.')
return
@@ -426,32 +444,40 @@ export const metricsLogic = kea<metricsLogicType>([
actions.setCreatingMetric(true)
try {
// A markdown metric is created as a stub; its definition is authored on the
- // metric page, where the editor has room.
+ // metric page, where the editor has room. The null definition makes an overwrite
+ // drop the existing query, which the markdown editor cannot open.
+ // Blank fields are sent as blank, so an overwrite clears the old values.
const created = await dataCatalogMetricsCreate(projectId(), {
name: form.name,
- display_name: form.display_name || undefined,
+ display_name: form.display_name,
description: form.description,
- unit: form.unit || undefined,
+ unit: form.unit,
...(form.definitionType === 'insight'
? { source_insight_short_id: form.sourceInsightShortId }
- : {}),
+ : { definition: null }),
created_source: 'user',
+ overwrite,
})
- actions.loadMetricsSuccess([created, ...values.allMetrics])
+ actions.loadMetricsSuccess(withCreatedMetric(values.allMetrics, created))
actions.closeNewMetricModal()
- lemonToast.success('Metric created')
+ lemonToast.success(overwrite ? 'Metric overwritten' : 'Metric created')
if (form.definitionType === 'markdown') {
router.actions.push(urls.dataCatalogMetric(created.name), { edit: 'definition' })
}
} catch (error) {
- lemonToast.error(
- apiErrorDetail(error) || 'Could not create the metric. Check the fields and try again.'
- )
+ const existing = existingMetricFromNameConflict(error)
+ if (existing) {
+ openOverwriteMetricDialog({ existing, onOverwrite: () => actions.createMetric(true, form) })
+ } else {
+ lemonToast.error(
+ apiErrorDetail(error) || 'Could not create the metric. Check the fields and try again.'
+ )
+ }
} finally {
actions.setCreatingMetric(false)
}
},
- createMetricFromInsight: async ({ request }) => {
+ createMetricFromInsight: async ({ request, overwrite }) => {
if (values.isCreatingMetric) {
return
}
@@ -459,20 +485,32 @@ export const metricsLogic = kea<metricsLogicType>([
try {
const created = await dataCatalogMetricsCreate(projectId(), {
name: request.name,
- display_name: request.display_name || undefined,
+ display_name: request.display_name,
description: request.description,
source_insight_short_id: request.source_insight_short_id,
+ created_source: 'user',
+ overwrite,
})
- actions.loadMetricsSuccess([created, ...values.allMetrics])
+ actions.loadMetricsSuccess(withCreatedMetric(values.allMetrics, created))
actions.closeMetricFromInsightModal()
- lemonToast.success('Metric created from insight', {
+ lemonToast.success(overwrite ? 'Metric overwritten from insight' : 'Metric created from insight', {
button: {
label: 'View metric',
action: () => router.actions.push(urls.dataCatalogMetric(created.name)),
},
})
} catch (error) {
- lemonToast.error(apiErrorDetail(error) || 'Could not create the metric from this insight. Try again.')
+ const existing = existingMetricFromNameConflict(error)
+ if (existing) {
+ openOverwriteMetricDialog({
+ existing,
+ onOverwrite: () => actions.createMetricFromInsight(request, true),
+ })
+ } else {
+ lemonToast.error(
+ apiErrorDetail(error) || 'Could not create the metric from this insight. Try again.'
+ )
+ }
} finally {
actions.setCreatingMetric(false)
}
diff --git a/products/data_catalog/frontend/openOverwriteMetricDialog.test.tsx b/products/data_catalog/frontend/openOverwriteMetricDialog.test.tsx
new file mode 100644
index 000000000000..b27f5feb5c3f
--- /dev/null
+++ b/products/data_catalog/frontend/openOverwriteMetricDialog.test.tsx
@@ -0,0 +1,42 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'
+import { router } from 'kea-router'
+
+import { initKeaTests } from '~/test/init'
+
+import { openOverwriteMetricDialog } from './openOverwriteMetricDialog'
+
+const TITLE = 'Overwrite the existing metric?'
+
+describe('openOverwriteMetricDialog', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ [
+ 'the close icon',
+ 1,
+ 0,
+ async (): Promise<void> => void fireEvent.click(await screen.findByLabelText('close')),
+ ],
+ ['Overwrite', 0, 1, async (): Promise<void> => void fireEvent.click(await screen.findByText('Overwrite'))],
+ ['navigation', 0, 0, async (): Promise<void> => router.actions.push('/elsewhere')],
+ ])('closed by %s: runs onCancel %i times and onOverwrite %i times', async (_how, cancels, overwrites, close) => {
+ const onOverwrite = jest.fn()
+ const onCancel = jest.fn()
+ openOverwriteMetricDialog({ existing: { name: 'mrr', status: 'approved' }, onOverwrite, onCancel })
+ await screen.findByText(TITLE)
+
+ await close()
+ await waitFor(() => expect(screen.queryByText(TITLE)).not.toBeInTheDocument())
+
+ expect(onCancel).toHaveBeenCalledTimes(cancels)
+ expect(onOverwrite).toHaveBeenCalledTimes(overwrites)
+ })
+})
diff --git a/products/data_catalog/frontend/openOverwriteMetricDialog.tsx b/products/data_catalog/frontend/openOverwriteMetricDialog.tsx
new file mode 100644
index 000000000000..3c205734b66a
--- /dev/null
+++ b/products/data_catalog/frontend/openOverwriteMetricDialog.tsx
@@ -0,0 +1,52 @@
+import { router } from 'kea-router'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+
+import type { DataCatalogMetricNameConflictExistingApi } from './generated/api.schemas'
+
+export function openOverwriteMetricDialog({
+ existing,
+ onOverwrite,
+ onCancel,
+}: {
+ existing: DataCatalogMetricNameConflictExistingApi
+ onOverwrite: () => void
+ onCancel?: () => void
+}): void {
+ // Escape, the close icon, and an outside click skip the buttons, so every close that is not an overwrite counts as a cancel.
+ // A close caused by navigation is the exception, because the cancel path would reopen the save form on the next page.
+ let overwriting = false
+ const openedAt = router.values.location.pathname
+ LemonDialog.open({
+ title: 'Overwrite the existing metric?',
+ content: (
+ <div className="flex flex-col gap-2 text-sm text-secondary">
+ <span>
+ A metric named <code>{existing.name}</code> already exists. Overwriting it replaces its fields with
+ the values you entered.
+ </span>
+ {existing.status === 'approved' && (
+ <span>
+ This metric is approved. If you change its description, unit, or definition, it goes back to
+ proposed and needs approval again.
+ </span>
+ )}
+ </div>
+ ),
+ primaryButton: {
+ children: 'Overwrite',
+ status: 'danger',
+ onClick: () => {
+ overwriting = true
+ onOverwrite()
+ },
+ 'data-attr': 'data-catalog-overwrite-metric-confirm',
+ },
+ secondaryButton: { children: 'Cancel' },
+ onAfterClose: () => {
+ if (!overwriting && router.values.location.pathname === openedAt) {
+ onCancel?.()
+ }
+ },
+ })
+}