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.

refactor(insights): stop writing the deprecated dashboards list (#126284)

Thomas Obermüllere0e8b72acb8f
diff --git a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts
index 8c0e2fae7fb2..5a8abc2b93ee 100644
--- a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts
+++ b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts
@@ -3,8 +3,10 @@ import { MOCK_USER_UUID } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
+import { insightsApi } from 'scenes/insights/utils/api'
import { useMocks } from '~/mocks/jest'
import { dashboardsModel } from '~/models/dashboardsModel'
@@ -20,6 +22,8 @@ import {
UserBasicType,
} from '~/types'
+import * as dashboardsApi from 'products/dashboards/frontend/generated/api'
+
import { addToDashboardModalLogic } from './addToDashboardModalLogic'
const Insight1 = '1' as InsightShortId
@@ -104,6 +108,7 @@ describe('addToDashboardModalLogic', () => {
})
afterEach(() => {
+ jest.restoreAllMocks()
logic?.unmount()
// Tests may set `current_user: null`; clear so the next test gets a fresh `initKeaTests` bootstrap.
delete window.POSTHOG_APP_CONTEXT
@@ -122,7 +127,8 @@ describe('addToDashboardModalLogic', () => {
})
})
- it('addDashboardSuccess sets navigation target and triggers insight update', async () => {
+ it('addDashboardSuccess sets navigation target and adds the insight to the new dashboard', async () => {
+ jest.spyOn(dashboardsApi, 'dashboardsAddInsightCreate').mockResolvedValue({ id: 5, dashboard_id: 99 })
logic = addToDashboardModalLogic({ dashboardItemId: Insight1 })
logic.mount()
@@ -135,30 +141,45 @@ describe('addToDashboardModalLogic', () => {
await expectLogic(logic, () => {
dashboardsModel.actions.addDashboardSuccess(newDashboard)
})
- .toDispatchActions(['setDashboardToNavigateTo', 'addToDashboard', 'updateInsight'])
+ .toDispatchActions(['setDashboardToNavigateTo', 'addToDashboard', 'addInsightToDashboard'])
.toMatchValues({
_dashboardToNavigateTo: 99,
})
- // Let updateInsight settle before afterEach unmounts the logics it touches
+ // Let addInsightToDashboard settle before afterEach unmounts the logics it touches
.toFinishAllListeners()
})
it.each([
{
- name: 'adding keeps the dashboards the insight already sits on',
+ name: 'adding places the insight on the dashboard and keeps the others',
change: (modal: ReturnType<typeof addToDashboardModalLogic.build>) => modal.actions.addToDashboard(4),
+ endpoint: 'dashboardsAddInsightCreate' as const,
+ expectedRequest: [4, { insight_id: 1 }],
expectedDashboards: [1, 2, 4],
},
{
- name: 'removing keeps the other dashboards',
+ name: 'removing deletes the tile on that dashboard and keeps the others',
change: (modal: ReturnType<typeof addToDashboardModalLogic.build>) => modal.actions.removeFromDashboard(2),
+ endpoint: 'dashboardsDeleteTile' as const,
+ expectedRequest: [2, { tile_id: 12 }],
expectedDashboards: [1],
},
- ])('$name', async ({ change, expectedDashboards }) => {
+ ])('$name', async ({ change, endpoint, expectedRequest, expectedDashboards }) => {
const updateSpy = jest.spyOn(api.insights, 'update')
+ jest.spyOn(dashboardsApi, 'dashboardsAddInsightCreate').mockResolvedValue({ id: 14, dashboard_id: 4 })
+ jest.spyOn(dashboardsApi, 'dashboardsDeleteTile').mockResolvedValue()
+ jest.spyOn(insightsApi, 'getByNumericId').mockResolvedValue({
+ ...MOCK_INSIGHT,
+ dashboard_tiles: expectedDashboards.map((dashboardId) => ({
+ id: 10 + dashboardId,
+ dashboard_id: dashboardId,
+ })),
+ })
const insightProps = { dashboardItemId: Insight1 }
const insightLog = insightLogic(insightProps)
insightLog.mount()
+ // The mount loads the insight, and that load must not land after the change below.
+ await expectLogic(insightLog).toFinishAllListeners()
insightLog.actions.loadInsightSuccess({
...MOCK_INSIGHT,
dashboard_tiles: [
@@ -173,7 +194,9 @@ describe('addToDashboardModalLogic', () => {
await expectLogic(logic, () => change(logic)).toFinishAllListeners()
- expect(updateSpy.mock.calls[0][1].dashboards).toEqual(expectedDashboards)
+ expect(dashboardsApi[endpoint]).toHaveBeenCalledWith(expect.any(String), ...expectedRequest)
+ expect(updateSpy).not.toHaveBeenCalled()
+ expect(liveDashboardIds(insightLog.values.insight.dashboard_tiles)).toEqual(expectedDashboards)
})
it('orders dashboards: on insight first, then mine, then others pinned, then the rest', async () => {
diff --git a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts
index a85d2c6fa088..c0be4123b05a 100644
--- a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts
+++ b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.ts
@@ -55,33 +55,62 @@ export interface addToDashboardModalLogicActions {
dashboardId: number | null
insight: Partial<InsightModel<Node<Record<string, any>>>> | null
} // eventUsageLogic
- updateInsight: (
- insightUpdate: Partial<InsightModel<Node<Record<string, any>>>>,
+ addInsightToDashboard: (
+ dashboardId: number,
callback?: (() => void) | undefined
) => {
callback: (() => void) | undefined
- insightUpdate: Partial<InsightModel<Node<Record<string, any>>>>
+ dashboardId: number
+ } // insightLogic
+ addInsightToDashboardFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // insightLogic
+ addInsightToDashboardSuccess: (
+ insight: InsightModel<Node<Record<string, any>>>,
+ payload?:
+ | {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ | undefined
+ ) => {
+ insight: InsightModel<Node<Record<string, any>>>
+ payload?: {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
} // insightLogic
- updateInsightFailure: (
+ removeInsightFromDashboard: (
+ dashboardId: number,
+ callback?: (() => void) | undefined
+ ) => {
+ callback: (() => void) | undefined
+ dashboardId: number
+ } // insightLogic
+ removeInsightFromDashboardFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
} // insightLogic
- updateInsightSuccess: (
- insight: Partial<InsightModel<Node<Record<string, any>>>>,
+ removeInsightFromDashboardSuccess: (
+ insight: InsightModel<Node<Record<string, any>>>,
payload?:
| {
callback: (() => void) | undefined
- insightUpdate: Partial<InsightModel<Node<Record<string, any>>>>
+ dashboardId: number
}
| undefined
) => {
- insight: Partial<InsightModel<Node<Record<string, any>>>>
+ insight: InsightModel<Node<Record<string, any>>>
payload?: {
callback: (() => void) | undefined
- insightUpdate: Partial<InsightModel<Node<Record<string, any>>>>
+ dashboardId: number
}
} // insightLogic
showNewDashboardModal: () => {
@@ -140,6 +169,13 @@ export type addToDashboardModalLogicType = MakeLogicType<
addToDashboardModalLogicMeta
>
+function showDashboardUpdateError(errorObject: unknown): void {
+ // Surface hard rejections (e.g. the target dashboard is publicly shared and the
+ // editor lacks access to this insight's tables) - the modal otherwise fails silently.
+ const detail = (errorObject as { detail?: unknown } | null)?.detail
+ lemonToast.error(typeof detail === 'string' ? detail : 'Could not update dashboards')
+}
+
export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([
props({} as InsightLogicProps),
key(keyForInsightLogicProps('new')),
@@ -148,7 +184,14 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([
values: [insightLogic(props), ['insight'], userLogic, ['user']],
actions: [
insightLogic(props),
- ['updateInsight', 'updateInsightSuccess', 'updateInsightFailure'],
+ [
+ 'addInsightToDashboard',
+ 'addInsightToDashboardSuccess',
+ 'addInsightToDashboardFailure',
+ 'removeInsightFromDashboard',
+ 'removeInsightFromDashboardSuccess',
+ 'removeInsightFromDashboardFailure',
+ ],
eventUsageLogic,
['reportSavedInsightToDashboard', 'reportRemovedInsightFromDashboard', 'reportCreatedDashboardFromModal'],
newDashboardLogic,
@@ -171,8 +214,10 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([
{
addToDashboard: (_, { dashboardId }) => dashboardId,
removeFromDashboard: (_, { dashboardId }) => dashboardId,
- updateInsightSuccess: () => null,
- updateInsightFailure: () => null,
+ addInsightToDashboardSuccess: () => null,
+ addInsightToDashboardFailure: () => null,
+ removeInsightFromDashboardSuccess: () => null,
+ removeInsightFromDashboardFailure: () => null,
},
],
_dashboardToNavigateTo: [
@@ -251,49 +296,34 @@ export const addToDashboardModalLogic = kea<addToDashboardModalLogicType>([
actions.setScrollIndex(values.orderedDashboards.findIndex((d) => d.id === dashboard.id))
},
- updateInsightFailure: ({ errorObject }) => {
- // Surface hard rejections (e.g. the target dashboard is publicly shared and the
- // editor lacks access to this insight's tables) - the modal otherwise fails silently.
- const detail = (errorObject as { detail?: unknown } | null)?.detail
- lemonToast.error(typeof detail === 'string' ? detail : 'Could not update dashboards')
+ addInsightToDashboardFailure: ({ errorObject }) => {
+ showDashboardUpdateError(errorObject)
+ },
+ removeInsightFromDashboardFailure: ({ errorObject }) => {
+ showDashboardUpdateError(errorObject)
},
addToDashboard: async ({ dashboardId }) => {
- // TODO be able to update not by patching `dashboards` against insight
- // either patch dashboard_tiles on the insight or add a dashboard_tiles API
- actions.updateInsight(
- {
- dashboards: [...liveDashboardIds(values.insight.dashboard_tiles), dashboardId],
- },
- () => {
- actions.reportSavedInsightToDashboard(values.insight, dashboardId)
- dashboardsModel.actions.tileAddedToDashboard(dashboardId)
- if (values._dashboardToNavigateTo === dashboardId) {
- actions.setDashboardToNavigateTo(null)
- router.actions.push(urls.dashboard(dashboardId))
- } else {
- lemonToast.success('Insight added to dashboard', {
- button: {
- label: 'View dashboard',
- action: () => router.actions.push(urls.dashboard(dashboardId)),
- },
- })
- }
+ actions.addInsightToDashboard(dashboardId, () => {
+ actions.reportSavedInsightToDashboard(values.insight, dashboardId)
+ dashboardsModel.actions.tileAddedToDashboard(dashboardId)
+ if (values._dashboardToNavigateTo === dashboardId) {
+ actions.setDashboardToNavigateTo(null)
+ router.actions.push(urls.dashboard(dashboardId))
+ } else {
+ lemonToast.success('Insight added to dashboard', {
+ button: {
+ label: 'View dashboard',
+ action: () => router.actions.push(urls.dashboard(dashboardId)),
+ },
+ })
}
- )
+ })
},
removeFromDashboard: async ({ dashboardId }): Promise<void> => {
- actions.updateInsight(
- {
- dashboards: liveDashboardIds(values.insight.dashboard_tiles).filter((d) => d !== dashboardId),
- dashboard_tiles: (values.insight.dashboard_tiles || []).filter(
- (dt) => dt.dashboard_id !== dashboardId
- ),
- },
- () => {
- actions.reportRemovedInsightFromDashboard(values.insight, dashboardId)
- lemonToast.success('Insight removed from dashboard')
- }
- )
+ actions.removeInsightFromDashboard(dashboardId, () => {
+ actions.reportRemovedInsightFromDashboard(values.insight, dashboardId)
+ lemonToast.success('Insight removed from dashboard')
+ })
},
})),
])
diff --git a/frontend/src/lib/utils/deleteWithUndo.test.tsx b/frontend/src/lib/utils/deleteWithUndo.test.tsx
index 17398e1ef0f6..d94161c6d727 100644
--- a/frontend/src/lib/utils/deleteWithUndo.test.tsx
+++ b/frontend/src/lib/utils/deleteWithUndo.test.tsx
@@ -1,8 +1,11 @@
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { insightsApi } from 'scenes/insights/utils/api'
-import { deleteWithUndo } from './deleteWithUndo'
+import { InsightModel } from '~/types'
+
+import { deleteInsightWithUndo, deleteWithUndo } from './deleteWithUndo'
describe('deleteWithUndo', () => {
let updateSpy: jest.SpyInstance
@@ -64,4 +67,26 @@ describe('deleteWithUndo', () => {
expect(errorSpy).toHaveBeenCalledTimes(toasts)
expect(onError).toHaveBeenCalledWith(false, { id: 7 })
})
+
+ it('restores an insight even when one of its dashboards refuses the tile', async () => {
+ const warningSpy = jest.spyOn(lemonToast, 'warning')
+ jest.spyOn(insightsApi, 'addToDashboard')
+ .mockResolvedValueOnce({ id: 11, dashboard_id: 1 })
+ .mockRejectedValueOnce({ status: 404, detail: 'Not found.' })
+ const callback = jest.fn()
+ const insight = {
+ id: 7,
+ name: 'Weekly signups',
+ dashboard_tiles: [
+ { id: 11, dashboard_id: 1 },
+ { id: 12, dashboard_id: 2 },
+ ],
+ } as InsightModel
+
+ await deleteInsightWithUndo({ undo: true, endpoint: 'projects/1/insights', object: insight, callback })
+
+ expect(updateSpy).toHaveBeenCalledWith('api/projects/1/insights/7', expect.objectContaining({ deleted: false }))
+ expect(callback).toHaveBeenCalledWith(true, insight)
+ expect(warningSpy).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/frontend/src/lib/utils/deleteWithUndo.tsx b/frontend/src/lib/utils/deleteWithUndo.tsx
index 44e34ac46da0..b298e34377a3 100644
--- a/frontend/src/lib/utils/deleteWithUndo.tsx
+++ b/frontend/src/lib/utils/deleteWithUndo.tsx
@@ -1,6 +1,7 @@
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { retryImport } from 'lib/utils/retryImport'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
@@ -69,19 +70,29 @@ export async function deleteInsightWithUndo({
endpoint: string
object: InsightModel
idField?: keyof InsightModel
+ /** The dashboards an undo puts the insight back on. Defaults to the dashboards its live tiles sit on. */
+ dashboardIds?: number[]
callback?: (undo: boolean, object: InsightModel) => void
}): Promise<void> {
try {
+ const { dashboards: _dashboards, ...insight } = props.object
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
await api.update(`api/${props.endpoint}/${props.object[props.idField || 'id']}`, {
- ...props.object,
- // The body is the whole insight, so it carries the insight's dashboards too. An explicit
- // `dashboards` on the object replaces the list read from the tiles.
- dashboards:
- props.object.dashboards ??
- (props.object.dashboard_tiles ? liveDashboardIds(props.object.dashboard_tiles) : undefined),
+ ...insight,
deleted: !undo,
})
+ let dashboardsNotRestored = 0
+ if (undo) {
+ // Loaded on demand: a static import would put the insights API on every page's eager path.
+ const { insightsApi } = await retryImport(() => import('scenes/insights/utils/api'))
+ // Each add restores a tile the delete hid. One refused dashboard must not skip the updates below.
+ const placements = await Promise.allSettled(
+ (props.dashboardIds ?? liveDashboardIds(props.object.dashboard_tiles)).map((dashboardId) =>
+ insightsApi.addToDashboard(props.object.id, dashboardId)
+ )
+ )
+ dashboardsNotRestored = placements.filter((placement) => placement.status === 'rejected').length
+ }
props.callback?.(undo, props.object)
if (props.object.short_id) {
if (undo) {
@@ -105,6 +116,11 @@ export async function deleteInsightWithUndo({
},
}
)
+ if (dashboardsNotRestored > 0) {
+ lemonToast.warning(
+ `The insight is back, but it couldn't be put back on ${dashboardsNotRestored} of its dashboards. Add it to them from the insight page.`
+ )
+ }
} catch (error: any) {
// Show error toast with the error message from the API
const errorMessage = error.detail || error.message || 'Failed to delete'
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 830ebb38216f..854e3b633f29 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -5046,7 +5046,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
other_dashboard_count: otherDashboardCount,
})
return deleteInsightWithUndo({
- object: { ...insight, dashboards: dashboardIds },
+ object: insight,
+ dashboardIds,
endpoint: `projects/${values.currentTeamId}/insights`,
callback: (undo) => {
const updatedInsight = {
diff --git a/frontend/src/scenes/dashboard/liveDashboardIds.ts b/frontend/src/scenes/dashboard/liveDashboardIds.ts
index b6a57c52663e..b4faabf45823 100644
--- a/frontend/src/scenes/dashboard/liveDashboardIds.ts
+++ b/frontend/src/scenes/dashboard/liveDashboardIds.ts
@@ -2,8 +2,7 @@ import { DashboardTileBasicType } from '~/types'
/**
* Soft-deleted tiles do not count, because the backend does not count them either. Session responses omit
- * the deprecated insight `dashboards` field, and a PATCH of it replaces the whole membership, so a writer
- * builds the new list from this one.
+ * the deprecated insight `dashboards` field, so this is the list of dashboards an insight sits on.
*/
export function liveDashboardIds(tiles: DashboardTileBasicType[] | null | undefined): number[] {
return (tiles || []).filter((tile) => !tile.deleted).map((tile) => tile.dashboard_id)
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 51eaef4ea955..bca065198d85 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -5,6 +5,7 @@ import { expectLogic, partial } from 'kea-test-utils'
import { LemonDialog } from '@posthog/lemon-ui'
+import { ApiError } from 'lib/api'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -3538,8 +3539,8 @@ describe('sqlEditorLogic', () => {
})
it.each([
- { name: 'passes dashboards to insightsApi.create when a dashboardId is set', dashboardId: DASHBOARD_ID },
- { name: 'does not pass dashboards to insightsApi.create when no dashboardId is set', dashboardId: null },
+ { name: 'creates the insight on the dashboard when a dashboardId is set', dashboardId: DASHBOARD_ID },
+ { name: 'creates the insight on no dashboard when no dashboardId is set', dashboardId: null },
])('$name', async ({ dashboardId }) => {
const createSpy = jest.spyOn(insightsApi, 'create').mockResolvedValue(MOCK_INSIGHT)
@@ -3567,58 +3568,55 @@ describe('sqlEditorLogic', () => {
saved: true,
query: { source: { query: 'SELECT 42 AS unrun_edit' } },
})
- if (dashboardId !== null) {
- expect(createPayload.dashboards).toEqual([dashboardId])
- } else {
- expect(createPayload).not.toHaveProperty('dashboards')
- }
+ expect(createPayload).not.toHaveProperty('dashboards')
+ expect(createSpy.mock.calls[0][1]).toEqual(dashboardId !== null ? [dashboardId] : [])
})
- // The update path unions the target dashboard with the insight's existing links from
- // dashboard_tiles, deduped.
it.each([
- {
- name: 'merges the dashboard with existing dashboard_tiles links',
- dashboardTiles: [{ id: 1, dashboard_id: 7 }],
- expected: [7, DASHBOARD_ID],
- },
- {
- name: 'does not duplicate a dashboard the insight is already linked to',
- dashboardTiles: [{ id: 1, dashboard_id: DASHBOARD_ID }],
- expected: [DASHBOARD_ID],
- },
- ])('$name', async ({ dashboardTiles, expected }) => {
- const updateSpy = jest.spyOn(insightsApi, 'update').mockResolvedValue(MOCK_INSIGHT)
-
- logic = sqlEditorLogic({
- tabId: TAB_ID,
- monaco: createMockMonaco(),
- editor: createMockEditor(),
- })
- logic.mount()
- editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
- editorRootLogic.mount()
-
- const insightOnDashboards = {
- ...MOCK_INSIGHT,
- dashboard_tiles: dashboardTiles,
- } as InsightModel
- logic.actions.editInsight(MOCK_INSIGHT_QUERY.source.query, insightOnDashboards)
- await expectLogic(logic)
- .toDispatchActions(['createTab', 'updateTab'])
- .toMatchValues({ editingInsight: partial({ short_id: MOCK_INSIGHT_SHORT_ID }) })
+ { placement: 'accepted', expectedPath: `/dashboard/${DASHBOARD_ID}` },
+ { placement: 'refused', expectedPath: `/insights/${MOCK_INSIGHT_SHORT_ID}` },
+ ])(
+ 'saving an existing insight from a dashboard flow, placement $placement',
+ async ({ placement, expectedPath }) => {
+ const updateSpy = jest.spyOn(insightsApi, 'update').mockResolvedValue(MOCK_INSIGHT)
+ const addToDashboardSpy = jest.spyOn(insightsApi, 'addToDashboard')
+ if (placement === 'accepted') {
+ addToDashboardSpy.mockResolvedValue({ id: 2, dashboard_id: DASHBOARD_ID })
+ } else {
+ addToDashboardSpy.mockRejectedValue(new ApiError('Non-OK response', 403))
+ }
- logic.actions.setDashboardId(DASHBOARD_ID)
- logic.actions.setQueryInput('SELECT 42 AS unrun_edit')
- logic.actions.updateInsight()
- await expectLogic(logic).toFinishAllListeners()
+ logic = sqlEditorLogic({
+ tabId: TAB_ID,
+ monaco: createMockMonaco(),
+ editor: createMockEditor(),
+ })
+ logic.mount()
+ editorRootLogic = editorSceneLogic({ tabId: TAB_ID })
+ editorRootLogic.mount()
- expect(updateSpy).toHaveBeenCalledTimes(1)
- const [, updatePayload] = updateSpy.mock.calls[0]
- expect(updatePayload.query).toMatchObject({ source: { query: 'SELECT 42 AS unrun_edit' } })
- // Order-independent: only the set of linked dashboards matters.
- expect([...(updatePayload.dashboards ?? [])].sort()).toEqual([...expected].sort())
- })
+ const insightOnDashboards = {
+ ...MOCK_INSIGHT,
+ dashboard_tiles: [{ id: 1, dashboard_id: 7 }],
+ } as InsightModel
+ logic.actions.editInsight(MOCK_INSIGHT_QUERY.source.query, insightOnDashboards)
+ await expectLogic(logic)
+ .toDispatchActions(['createTab', 'updateTab'])
+ .toMatchValues({ editingInsight: partial({ short_id: MOCK_INSIGHT_SHORT_ID }) })
+
+ logic.actions.setDashboardId(DASHBOARD_ID)
+ logic.actions.setQueryInput('SELECT 42 AS unrun_edit')
+ logic.actions.updateInsight()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(updateSpy).toHaveBeenCalledTimes(1)
+ const [, updatePayload] = updateSpy.mock.calls[0]
+ expect(updatePayload.query).toMatchObject({ source: { query: 'SELECT 42 AS unrun_edit' } })
+ expect(updatePayload).not.toHaveProperty('dashboards')
+ expect(addToDashboardSpy).toHaveBeenCalledWith(MOCK_INSIGHT.id, DASHBOARD_ID)
+ expect(router.values.location.pathname).toContain(expectedPath)
+ }
+ )
})
describe('materialize on save', () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index ca1b8051eee5..fbe429ef8766 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -50,7 +50,6 @@ import { lazyWithRetry } from 'lib/utils/retryImport'
import { slugify } from 'lib/utils/strings'
import { backLinkParams, withBackLink } from 'scenes/analytics/analyticsBackLink'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import {
MANAGED_TRINO_SCHEMA_SCOPE,
databaseTableListLogic,
@@ -598,6 +597,35 @@ export function tabModelPath(tabId: string): string {
return `tab-${tabId}`
}
+/** The update has landed when this runs, so a refused placement shows a toast instead of throwing, and the caller still syncs its state. */
+async function placeSavedInsightOnDashboard(
+ savedInsight: InsightModel,
+ dashboardId: number | null
+): Promise<{ insight: InsightModel; placed: boolean }> {
+ if (!dashboardId) {
+ return { insight: savedInsight, placed: false }
+ }
+ try {
+ const tile = await insightsApi.addToDashboard(savedInsight.id, dashboardId)
+ return {
+ insight: {
+ ...savedInsight,
+ dashboard_tiles: [
+ ...(savedInsight.dashboard_tiles || []).filter((t) => t.dashboard_id !== dashboardId),
+ tile,
+ ],
+ },
+ placed: true,
+ }
+ } catch (e) {
+ const detail = e instanceof ApiError ? e.detail : null
+ lemonToast.error(
+ `Insight saved, but it couldn't be added to the dashboard. ${detail ?? 'Add it from the insight page instead.'}`
+ )
+ return { insight: savedInsight, placed: false }
+ }
+}
+
// Apply `text` to the tab's persistent Monaco model as a single undoable edit. The model is
// kept alive across the diff <-> editor swap by `keepCurrentModel` (see QueryWindow), so its
// full undo history survives — pushEditOperations adds one more undoable step rather than
@@ -2918,12 +2946,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
const dashboardId = values.dashboardId
- const insight = await insightsApi.create({
- name,
- query: sourceQueryToSave,
- saved: true,
- ...(dashboardId ? { dashboards: [dashboardId] } : {}),
- })
+ const insight = await insightsApi.create(
+ { name, query: sourceQueryToSave, saved: true },
+ dashboardId ? [dashboardId] : []
+ )
captureBIEditorQuerySaved(biEditorState, 'insight', 'create', dashboardId !== null)
const logic = insightLogic({
dashboardItemId: insight.short_id,
@@ -3172,13 +3198,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
query: currentVisualizationQuery,
}
- // When saving from a dashboard flow, attach the tile server-side without
- // dropping the insight's existing dashboard links.
const dashboardId = values.dashboardId
- if (dashboardId) {
- const existingDashboardIds = liveDashboardIds(values.editingInsight.dashboard_tiles)
- insightRequest.dashboards = Array.from(new Set([...existingDashboardIds, dashboardId]))
- }
let savedInsight: InsightModel
try {
@@ -3192,6 +3212,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
throw e
}
+ const placement = await placeSavedInsightOnDashboard(savedInsight, dashboardId)
+ savedInsight = placement.insight
actions.setInsightLoading(false)
captureBIEditorQuerySaved(biEditorState, 'insight', 'update', dashboardId !== null)
@@ -3214,7 +3236,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
})
}
- if (dashboardId) {
+ if (dashboardId && placement.placed) {
dashboardsModel.findMounted()?.actions.updateDashboardInsight(savedInsight)
dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
action: DashboardLoadAction.Update,
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 4c8780e5fe9b..8e993ecceb10 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -36,6 +36,7 @@ import {
featureFlagLogic as sceneFeatureFlagLogic,
} from 'scenes/feature-flags/featureFlagLogic'
import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
+import { insightsApi } from 'scenes/insights/utils/api'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -2311,12 +2312,7 @@ export const experimentLogic = kea<experimentLogicType>([
for (const query of metrics) {
const insightQuery = queryBuilder(query)
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use insightsCreate() from 'products/product_analytics/frontend/generated/api' instead.
- await api.create(`api/projects/${projectLogic.values.currentProjectId}/insights`, {
- name: query.name || undefined,
- query: insightQuery,
- dashboards: [dashboard.id],
- })
+ await insightsApi.create({ name: query.name || undefined, query: insightQuery }, [dashboard.id])
}
}
diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.ts
index 3c6d4baec912..7badd9d19567 100644
--- a/frontend/src/scenes/insights/insightLogic.test.ts
+++ b/frontend/src/scenes/insights/insightLogic.test.ts
@@ -647,34 +647,55 @@ describe('insightLogic', () => {
})
test.each([
- [
- 'sends the dashboards its live tiles sit on',
- [...TILES_ON_DASHBOARDS_1_2_3, { id: 14, dashboard_id: 4, deleted: true }],
- [1, 2, 3],
- ],
- ['sends no dashboards while its tiles are not loaded', undefined, undefined],
- ])('saving a saved insight %s', async (_name, dashboardTiles, expectedDashboards) => {
- const updateSpy = jest.spyOn(api.insights, 'update')
- const insightProps: InsightLogicProps = {
- dashboardItemId: Insight42,
- cachedInsight: {
- id: 42,
- short_id: Insight42,
- query: examples.FunnelsQuery,
- result: {},
- dashboard_tiles: dashboardTiles,
+ {
+ name: 'a saved insight stays on the dashboards it sits on',
+ insightProps: {
+ dashboardItemId: Insight42,
+ cachedInsight: {
+ id: 42,
+ short_id: Insight42,
+ query: examples.FunnelsQuery,
+ result: {},
+ dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,
+ },
},
- }
- logic = insightLogic(insightProps)
- logic.mount()
- insightDataLogic(insightProps).mount()
+ expectedPlacements: [],
+ },
+ {
+ name: 'a new insight goes on the dashboard it was started from',
+ insightProps: {
+ dashboardItemId: 'new',
+ cachedInsight: { ...createEmptyInsight('new'), dashboards: [MOCK_DASHBOARD_ID] },
+ },
+ expectedPlacements: [[12, MOCK_DASHBOARD_ID]],
+ },
+ ] as { name: string; insightProps: InsightLogicProps; expectedPlacements: number[][] }[])(
+ 'saving: $name',
+ async ({ insightProps, expectedPlacements }) => {
+ const update = jest.spyOn(api, 'update')
+ const create = jest.spyOn(api, 'create')
+ const addToDashboard = jest
+ .spyOn(insightsApi, 'addToDashboard')
+ .mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
+ logic = insightLogic(insightProps)
+ logic.mount()
+ insightDataLogic(insightProps).mount()
- await expectLogic(logic, () => {
- logic.actions.saveInsight()
- }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.saveInsight()
+ }).toFinishAllListeners()
- expect(updateSpy.mock.calls[0][1].dashboards).toEqual(expectedDashboards)
- })
+ const insightWrites = [...update.mock.calls, ...create.mock.calls].filter(([url]) =>
+ /\/insights\/?(\d+\/?)?$/.test(url)
+ )
+ expect(insightWrites).toHaveLength(1)
+ expect(insightWrites[0][1]).not.toHaveProperty('dashboards')
+ expect(addToDashboard.mock.calls).toEqual(expectedPlacements)
+ update.mockRestore()
+ create.mockRestore()
+ addToDashboard.mockRestore()
+ }
+ )
test('updateInsight updates dashboards', async () => {
savedInsightsLogic().mount()
@@ -690,10 +711,12 @@ describe('insightLogic', () => {
await expectLogic(dashboardsModel).toDispatchActions(['updateDashboardInsight'])
})
- test('updateInsight resolves id from short_id when id is missing', async () => {
- // Simulates the race condition where updateInsight fires before loadInsight
- // completes: the insight has a short_id but no numeric id yet (e.g. when
- // adding to a dashboard immediately after saving a new insight).
+ test('addInsightToDashboard resolves id from short_id when id is missing', async () => {
+ // Simulates the race condition where the insight is added to a dashboard right after a new
+ // insight is saved, before loadInsight completes: it has a short_id but no numeric id yet.
+ const addToDashboard = jest
+ .spyOn(insightsApi, 'addToDashboard')
+ .mockResolvedValue({ id: 99, dashboard_id: MOCK_DASHBOARD_ID })
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: {
@@ -704,8 +727,11 @@ describe('insightLogic', () => {
logic.mount()
await expectLogic(logic, () => {
- logic.actions.updateInsight({ dashboards: [MOCK_DASHBOARD_ID] })
- }).toDispatchActions(['updateInsightSuccess'])
+ logic.actions.addInsightToDashboard(MOCK_DASHBOARD_ID)
+ }).toDispatchActions(['addInsightToDashboardSuccess'])
+
+ expect(addToDashboard).toHaveBeenCalledWith(42, MOCK_DASHBOARD_ID)
+ addToDashboard.mockRestore()
})
test('after save as from a dashboard tile, the editor state stays on the tile insight until navigation opens the copy', async () => {
@@ -1104,24 +1130,30 @@ describe('insightLogic', () => {
expect(api.update).toHaveBeenCalledWith(
expect.stringContaining('/insights/42'),
- expect.objectContaining({ deleted: true, dashboards: [1, 2, 3] })
+ expect.objectContaining({ deleted: true })
)
+ expect((api.update as jest.Mock).mock.calls[0][1]).not.toHaveProperty('dashboards')
const expectedUrl = dashboardId ? urls.dashboard(dashboardId) : urls.savedInsights()
await expectLogic(router).toDispatchActions([router.actionCreators.push(expectedUrl)])
})
- it('keeps the remaining dashboards in the delete request after one of them is deleted', async () => {
- jest.spyOn(api, 'update')
+ it('undo puts the insight back on its dashboards, except one deleted in the meantime', async () => {
+ const info = jest.spyOn(lemonToast, 'info')
+ const addToDashboard = jest
+ .spyOn(insightsApi, 'addToDashboard')
+ .mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
dashboardsModel.actions.deleteDashboardSuccess({ id: 3 } as DashboardType)
logic.actions.confirmDeleteInsight(null)
await expectLogic(logic).toFinishAllListeners()
+ await info.mock.calls[0][1]?.button?.action()
- expect(api.update).toHaveBeenCalledWith(
- expect.stringContaining('/insights/42'),
- expect.objectContaining({ deleted: true, dashboards: [1, 2] })
- )
+ expect(addToDashboard.mock.calls).toEqual([
+ [42, 1],
+ [42, 2],
+ ])
+ addToDashboard.mockRestore()
})
it('restores insight on undo from dashboard', async () => {
@@ -1156,6 +1188,9 @@ describe('insightLogic', () => {
it('fetches clean insight before duplicating', async () => {
jest.spyOn(api, 'create')
+ const addToDashboard = jest
+ .spyOn(insightsApi, 'addToDashboard')
+ .mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
logic.actions.duplicateInsight(logic.values.insight as InsightModel, true)
await expectLogic(logic).toFinishAllListeners()
@@ -1164,9 +1199,20 @@ describe('insightLogic', () => {
// not the one passed in (which may have dashboard filter overrides)
expect(api.create).toHaveBeenCalledWith(
expect.stringContaining('/insights'),
- expect.objectContaining({ name: 'original name (copy)', dashboards: [1, 2, 3] }),
+ expect.objectContaining({ name: 'original name (copy)' }),
expect.anything()
)
+ expect(api.create).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ dashboards: expect.anything() }),
+ expect.anything()
+ )
+ expect(addToDashboard.mock.calls).toEqual([
+ [12, 1],
+ [12, 2],
+ [12, 3],
+ ])
+ addToDashboard.mockRestore()
})
it('falls back to original insight when fetch fails', async () => {
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 1223d12f12bc..09e08aabc619 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -114,6 +114,30 @@ function reportInsightSaved(
export const UNSAVED_INSIGHT_MIN_REFRESH_INTERVAL_MINUTES = 3
+/** Right after a save the insight state can hold only the short ID, so the numeric ID is looked up from it. */
+async function resolveInsightId(insight: Partial<InsightModel>): Promise<number> {
+ const insightId = insight.id || (insight.short_id ? await getInsightId(insight.short_id) : undefined)
+ if (!insightId) {
+ throw new Error('Cannot update insight: unable to resolve insight id')
+ }
+ return insightId
+}
+
+// The tile endpoints return no insight, and this logic's copy can carry a dashboard's overrides in its query.
+async function reloadInsightAfterTileChange(
+ insightId: number,
+ currentResult: InsightModel['result'],
+ removedDashboardIds: number[]
+): Promise<InsightModel> {
+ const savedInsight = await insightsApi.getByNumericId(insightId)
+ if (!savedInsight) {
+ throw new Error('Cannot reload the insight after changing its dashboards')
+ }
+ const updatedInsight = { ...savedInsight, result: savedInsight.result || currentResult }
+ dashboardsModel.actions.updateDashboardInsight(updatedInsight, removedDashboardIds)
+ return updatedInsight
+}
+
export const createEmptyInsight = (shortId: InsightShortId | `new-${string}` | 'new'): Partial<InsightModel> => ({
short_id: shortId !== 'new' && !shortId.startsWith('new-') ? (shortId as InsightShortId) : undefined,
name: undefined,
@@ -191,6 +215,33 @@ export interface insightLogicActions {
value: true
} // tagsModel
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
+ addInsightToDashboard: (
+ dashboardId: number,
+ callback?: () => void
+ ) => {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ addInsightToDashboardFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ addInsightToDashboardSuccess: (
+ insight: InsightModel<Node<Record<string, any>>>,
+ payload?: {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ ) => {
+ insight: InsightModel<Node<Record<string, any>>>
+ payload?: {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ }
confirmDeleteInsight: (dashboardId: number | null) => {
dashboardId: number | null
}
@@ -342,6 +393,33 @@ export interface insightLogicActions {
reloadSavedInsights: () => {
value: true
}
+ removeInsightFromDashboard: (
+ dashboardId: number,
+ callback?: () => void
+ ) => {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ removeInsightFromDashboardFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ removeInsightFromDashboardSuccess: (
+ insight: InsightModel<Node<Record<string, any>>>,
+ payload?: {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ ) => {
+ insight: InsightModel<Node<Record<string, any>>>
+ payload?: {
+ callback: (() => void) | undefined
+ dashboardId: number
+ }
+ }
saveAs: (
redirectToViewMode?: boolean,
persist?: boolean,
@@ -662,6 +740,8 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
insightUpdate,
callback,
}),
+ addInsightToDashboard: (dashboardId: number, callback?: () => void) => ({ dashboardId, callback }),
+ removeInsightFromDashboard: (dashboardId: number, callback?: () => void) => ({ dashboardId, callback }),
setInsightMetadata: (
metadataUpdate: Partial<Pick<InsightModel, 'name' | 'description' | 'tags' | 'favorited'>>
) => ({
@@ -747,15 +827,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
if (!Object.entries(insightUpdate).length) {
return values.insight
}
- // Resolve the numeric ID. When updateInsight races with loadInsight
- // (e.g. adding to a dashboard right after save), values.insight.id
- // may still be undefined. Fall back to resolving via short_id.
- const insightId =
- values.insight.id ||
- (values.insight.short_id ? await getInsightId(values.insight.short_id) : undefined)
- if (!insightId) {
- throw new Error('Cannot update insight: unable to resolve insight id')
- }
+ const insightId = await resolveInsightId(values.insight)
const response = await insightsApi.update(insightId, insightUpdate)
// Call the callback before breakpoint so it fires even if a newer loader
// action was dispatched while the API call was in flight. The API call
@@ -776,6 +848,20 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
values.insight.short_id && refreshTreeItem('insight', String(values.insight.short_id))
return updatedInsight
},
+ addInsightToDashboard: async ({ dashboardId, callback }, breakpoint) => {
+ const insightId = await resolveInsightId(values.insight)
+ await insightsApi.addToDashboard(insightId, dashboardId)
+ callback?.()
+ breakpoint()
+ return await reloadInsightAfterTileChange(insightId, values.insight.result, [])
+ },
+ removeInsightFromDashboard: async ({ dashboardId, callback }, breakpoint) => {
+ const insightId = await resolveInsightId(values.insight)
+ await insightsApi.removeFromDashboard(values.insight, dashboardId)
+ callback?.()
+ breakpoint()
+ return await reloadInsightAfterTileChange(insightId, values.insight.result, [dashboardId])
+ },
setInsightMetadata: async ({ metadataUpdate }, breakpoint) => {
// new insight
if (values.insight.short_id == null) {
@@ -938,8 +1024,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
return {
...state,
dashboard_tiles: state.dashboard_tiles?.filter((tile) => tile.dashboard_id !== id),
- // An unsaved insight must not ask to be placed on the deleted dashboard. A saved insight has
- // no `dashboards`, and an `undefined` one would replace the list a write builds from the tiles.
+ // An unsaved insight must not be placed on the deleted dashboard when it is saved.
...(state.dashboards ? { dashboards: state.dashboards.filter((d: number) => d !== id) } : {}),
}
},
@@ -960,6 +1045,14 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
...insight,
query: insight.query || null,
}),
+ addInsightToDashboardSuccess: (state, { insight }) => ({
+ ...state,
+ dashboard_tiles: insight.dashboard_tiles,
+ }),
+ removeInsightFromDashboardSuccess: (state, { insight }) => ({
+ ...state,
+ dashboard_tiles: insight.dashboard_tiles,
+ }),
setInsightMetadataSuccess: (state, { insight }) => ({
...state,
name: insight.name,
@@ -1177,13 +1270,9 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
const insightNumericId =
values.insight.id || (values.insight.short_id ? await getInsightId(values.insight.short_id) : undefined)
const { name, description, favorited, deleted, tags } = values.insight
- // A new insight carries the dashboards to place it on. A saved one sends back the dashboards
- // it sits on. While its tiles are not loaded it sends nothing, because an empty list would
- // take it off every dashboard.
- const currentDashboards = values.insight.dashboard_tiles
+ const dashboards = insightNumericId
? liveDashboardIds(values.insight.dashboard_tiles)
- : undefined
- const dashboards = insightNumericId ? currentDashboards : values.insight.dashboards
+ : values.insight.dashboards
let savedInsight: InsightModel
@@ -1197,16 +1286,15 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
query: values.query,
deleted,
saved: true,
- dashboards,
tags,
}
savedInsight = insightNumericId
? await insightsApi.update(insightNumericId, insightRequest)
- : await insightsApi.create({
- ...insightRequest,
- _create_in_folder: folder ?? getLastNewFolder(),
- })
+ : await insightsApi.create(
+ { ...insightRequest, _create_in_folder: folder ?? getLastNewFolder() },
+ dashboards ?? []
+ )
actions.reloadSavedInsights() // Load insights afresh
void refreshMountedInsightAlerts(props, insightNumericId)
diff --git a/frontend/src/scenes/insights/utils/api.test.ts b/frontend/src/scenes/insights/utils/api.test.ts
new file mode 100644
index 000000000000..110bfc5a0bcc
--- /dev/null
+++ b/frontend/src/scenes/insights/utils/api.test.ts
@@ -0,0 +1,51 @@
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+import { InsightModel } from '~/types'
+
+import * as dashboardsApi from 'products/dashboards/frontend/generated/api'
+
+import { insightsApi } from './api'
+
+describe('insightsApi.create', () => {
+ beforeEach(() => {
+ initKeaTests()
+ jest.spyOn(api.insights, 'create').mockResolvedValue({ id: 12, dashboard_tiles: [] } as unknown as InsightModel)
+ jest.spyOn(api.insights, 'update').mockResolvedValue({} as InsightModel)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('places the new insight on each dashboard in order, without sending dashboards', async () => {
+ jest.spyOn(dashboardsApi, 'dashboardsAddInsightCreate').mockImplementation(async (_projectId, dashboardId) => ({
+ id: 100 + dashboardId,
+ dashboard_id: dashboardId,
+ }))
+
+ const insight = await insightsApi.create({ name: 'Weekly signups' }, [3, 4])
+
+ expect(api.insights.create).toHaveBeenCalledWith({ name: 'Weekly signups' })
+ expect((dashboardsApi.dashboardsAddInsightCreate as jest.Mock).mock.calls.map((call) => call.slice(1))).toEqual(
+ [
+ [3, { insight_id: 12 }],
+ [4, { insight_id: 12 }],
+ ]
+ )
+ expect(insight.dashboard_tiles).toEqual([
+ { id: 103, dashboard_id: 3 },
+ { id: 104, dashboard_id: 4 },
+ ])
+ expect(api.insights.update).not.toHaveBeenCalled()
+ })
+
+ it('deletes the new insight again when a dashboard refuses it', async () => {
+ const refusal = { status: 403, detail: "You don't have permission to add insights to this dashboard." }
+ jest.spyOn(dashboardsApi, 'dashboardsAddInsightCreate').mockRejectedValue(refusal)
+
+ await expect(insightsApi.create({ name: 'Weekly signups' }, [3])).rejects.toBe(refusal)
+
+ expect(api.insights.update).toHaveBeenCalledWith(12, { deleted: true }, undefined)
+ })
+})
diff --git a/frontend/src/scenes/insights/utils/api.ts b/frontend/src/scenes/insights/utils/api.ts
index 5622b5f8c280..451c429206a0 100644
--- a/frontend/src/scenes/insights/utils/api.ts
+++ b/frontend/src/scenes/insights/utils/api.ts
@@ -1,8 +1,10 @@
-import api, { ApiMethodOptions } from 'lib/api'
+import api, { ApiConfig, ApiError, ApiMethodOptions } from 'lib/api'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { DashboardFilter, HogQLVariable, RefreshType, TileFilters } from '~/queries/schema/schema-general'
-import { InsightShortId, InsightModel } from '~/types'
+import { DashboardTileBasicType, InsightShortId, InsightModel } from '~/types'
+
+import { dashboardsAddInsightCreate, dashboardsDeleteTile } from 'products/dashboards/frontend/generated/api'
async function _perform(
method: 'create' | 'update',
@@ -43,19 +45,82 @@ export const insightsApi = {
}
return legacyInsight
},
- async create(insight: Partial<InsightModel>): Promise<InsightModel> {
- return this._perform('create', insight)
+ async create(insight: Partial<InsightModel>, dashboardIds: number[] = []): Promise<InsightModel> {
+ const created = await this._perform('create', insight)
+ if (!dashboardIds.length) {
+ return created
+ }
+ const tiles = await this.addNewInsightToDashboards(created.id, dashboardIds)
+ return { ...created, dashboard_tiles: [...(created.dashboard_tiles || []), ...tiles] }
},
async update(id: number, insightUpdate: Partial<InsightModel>, options?: ApiMethodOptions): Promise<InsightModel> {
return this._perform('update', insightUpdate, id, options)
},
async duplicate(insight: InsightModel): Promise<InsightModel> {
- const { id, short_id, result, created_at, created_by, last_modified_at, last_modified_by, ...rest } = insight
- return this.create({
- // The copy goes on every dashboard the original sits on.
- ...(insight.dashboard_tiles ? { dashboards: liveDashboardIds(insight.dashboard_tiles) } : {}),
- ...rest,
- name: insight.name ? `${insight.name} (copy)` : insight.name,
+ const {
+ id,
+ short_id,
+ result,
+ created_at,
+ created_by,
+ last_modified_at,
+ last_modified_by,
+ dashboards,
+ dashboard_tiles,
+ ...rest
+ } = insight
+ // The copy goes on every dashboard the original sits on.
+ return this.create(
+ { ...rest, name: insight.name ? `${insight.name} (copy)` : insight.name },
+ liveDashboardIds(dashboard_tiles)
+ )
+ },
+ /** Places a saved insight on a dashboard. A removed tile comes back with its old layout. */
+ async addToDashboard(insightId: number, dashboardId: number): Promise<DashboardTileBasicType> {
+ const tile = await dashboardsAddInsightCreate(String(ApiConfig.getCurrentTeamId()), dashboardId, {
+ insight_id: insightId,
})
+ return { id: tile.id, dashboard_id: tile.dashboard_id }
+ },
+ /** A refusal deletes the just-created insight, so a refused create leaves no insight behind. */
+ async addNewInsightToDashboards(insightId: number, dashboardIds: number[]): Promise<DashboardTileBasicType[]> {
+ const tiles: DashboardTileBasicType[] = []
+ try {
+ for (const dashboardId of dashboardIds) {
+ tiles.push(await this.addToDashboard(insightId, dashboardId))
+ }
+ } catch (error) {
+ try {
+ await this._perform('update', { deleted: true }, insightId)
+ } catch {
+ throw new ApiError(
+ `Could not delete insight ${insightId} after a refused placement`,
+ undefined,
+ undefined,
+ {
+ detail: "The insight was created, but it couldn't be added to the dashboard. Open it from the insights list to try again.",
+ }
+ )
+ }
+ throw error
+ }
+ return tiles
+ },
+ async removeFromDashboard(
+ insight: { dashboard_tiles?: DashboardTileBasicType[] | null },
+ dashboardId: number
+ ): Promise<void> {
+ const tile = insight.dashboard_tiles?.find((tile) => tile.dashboard_id === dashboardId && !tile.deleted)
+ if (!tile) {
+ return
+ }
+ try {
+ await dashboardsDeleteTile(String(ApiConfig.getCurrentTeamId()), dashboardId, { tile_id: tile.id })
+ } catch (error) {
+ // A retry after a lost response finds the tile already removed.
+ if (!(error instanceof ApiError && error.status === 404)) {
+ throw error
+ }
+ }
},
}
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
index ae5096ec5a22..bfc43ef52020 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
@@ -14,6 +14,8 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { InsightModel } from '~/types'
+import * as dashboardsApi from 'products/dashboards/frontend/generated/api'
+
import { addSavedInsightsModalLogic, handleDashboardUpdateFailure } from './addSavedInsightsModalLogic'
const createInsight = (id: number, name = 'test'): InsightModel =>
@@ -272,6 +274,10 @@ describe('addSavedInsightsModalLogic', () => {
describe('dashboard membership updates', () => {
const MESSAGES = { timedOut: 'Timed out', failed: 'Failed to add' }
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
const insightOnDashboards = (dashboardIds: number[]): InsightModel =>
({
...createInsight(53),
@@ -282,32 +288,33 @@ describe('addSavedInsightsModalLogic', () => {
})),
}) as InsightModel
- it('keeps the other dashboards when adding', async () => {
- initKeaTests()
- const update = jest.spyOn(insightsApi, 'update').mockResolvedValue(createInsight(53))
- const logic = addSavedInsightsModalLogic()
- logic.mount()
-
- await expectLogic(logic, () =>
- logic.actions.addInsightToDashboard(insightOnDashboards([7, 8]), 9)
- ).toFinishAllListeners()
-
- expect(update).toHaveBeenCalledWith(53, { dashboards: [7, 8, 9] })
-
- logic.unmount()
- })
-
- it('keeps the other dashboards when removing', async () => {
+ it.each([
+ {
+ name: 'adding places the insight on that dashboard',
+ change: (logic: ReturnType<typeof addSavedInsightsModalLogic.build>) =>
+ logic.actions.addInsightToDashboard(insightOnDashboards([7, 8]), 9),
+ endpoint: 'dashboardsAddInsightCreate' as const,
+ expectedRequest: [9, { insight_id: 53 }],
+ },
+ {
+ name: 'removing deletes the tile on that dashboard only',
+ change: (logic: ReturnType<typeof addSavedInsightsModalLogic.build>) =>
+ logic.actions.removeInsightFromDashboard(insightOnDashboards([7, 8]), 8),
+ endpoint: 'dashboardsDeleteTile' as const,
+ expectedRequest: [8, { tile_id: 2 }],
+ },
+ ])('$name', async ({ change, endpoint, expectedRequest }) => {
initKeaTests()
- const update = jest.spyOn(insightsApi, 'update').mockResolvedValue(createInsight(53))
+ const update = jest.spyOn(insightsApi, 'update')
+ jest.spyOn(dashboardsApi, 'dashboardsAddInsightCreate').mockResolvedValue({ id: 3, dashboard_id: 9 })
+ jest.spyOn(dashboardsApi, 'dashboardsDeleteTile').mockResolvedValue()
const logic = addSavedInsightsModalLogic()
logic.mount()
- await expectLogic(logic, () =>
- logic.actions.removeInsightFromDashboard(insightOnDashboards([7, 8]), 8)
- ).toFinishAllListeners()
+ await expectLogic(logic, () => change(logic)).toFinishAllListeners()
- expect(update).toHaveBeenCalledWith(53, { dashboards: [7] })
+ expect(dashboardsApi[endpoint]).toHaveBeenCalledWith(expect.any(String), ...expectedRequest)
+ expect(update).not.toHaveBeenCalled()
logic.unmount()
})
@@ -318,7 +325,7 @@ describe('addSavedInsightsModalLogic', () => {
])('handles a %s instead of filing an unhandled rejection', async (status, detail) => {
initKeaTests()
const toastError = jest.spyOn(lemonToast, 'error').mockImplementation()
- jest.spyOn(insightsApi, 'update').mockRejectedValue(
+ jest.spyOn(insightsApi, 'addToDashboard').mockRejectedValue(
new ApiError('Non-OK response', status, undefined, { detail })
)
const logic = addSavedInsightsModalLogic()
@@ -368,7 +375,7 @@ describe('addSavedInsightsModalLogic', () => {
const dashboard = dashboardLogic({ id: 1, dashboard: dashboardResult(1, []) })
dashboard.mount()
const loadDashboard = jest.spyOn(dashboard.actions, 'loadDashboard').mockImplementation()
- jest.spyOn(insightsApi, 'update').mockResolvedValue(createInsight(1))
+ jest.spyOn(insightsApi, 'addToDashboard').mockResolvedValue({ id: 3, dashboard_id: 1 })
const logic = addSavedInsightsModalLogic()
logic.mount()
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
index 58e38c111f6e..61993b60d7d5 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
@@ -12,7 +12,6 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -388,16 +387,18 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([
addInsightToDashboard: async ({ insight, dashboardId }) => {
try {
actions.setDashboardUpdateLoading(insight.id, true)
- const response = await insightsApi.update(insight.id, {
- dashboards: [...liveDashboardIds(insight.dashboard_tiles), dashboardId],
+ const tile = await insightsApi.addToDashboard(insight.id, dashboardId)
+ actions.updateInsight({
+ ...insight,
+ dashboard_tiles: [
+ ...(insight.dashboard_tiles || []).filter((t) => t.dashboard_id !== dashboardId),
+ tile,
+ ],
})
- if (response) {
- actions.updateInsight(response)
- dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
- action: DashboardLoadAction.Update,
- })
- lemonToast.success('Insight added to dashboard')
- }
+ dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
+ action: DashboardLoadAction.Update,
+ })
+ lemonToast.success('Insight added to dashboard')
} catch (e) {
actions.dashboardUpdateFailed(insight.id)
handleDashboardUpdateFailure(e, {
@@ -412,16 +413,15 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([
removeInsightFromDashboard: async ({ insight, dashboardId }) => {
try {
actions.setDashboardUpdateLoading(insight.id, true)
- const response = await insightsApi.update(insight.id, {
- dashboards: liveDashboardIds(insight.dashboard_tiles).filter((d) => d !== dashboardId),
+ await insightsApi.removeFromDashboard(insight, dashboardId)
+ actions.updateInsight({
+ ...insight,
+ dashboard_tiles: (insight.dashboard_tiles || []).filter((t) => t.dashboard_id !== dashboardId),
})
- if (response) {
- actions.updateInsight(response)
- dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
- action: DashboardLoadAction.Update,
- })
- lemonToast.success('Insight removed from dashboard')
- }
+ dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
+ action: DashboardLoadAction.Update,
+ })
+ lemonToast.success('Insight removed from dashboard')
} catch (e) {
actions.dashboardUpdateFailed(insight.id)
handleDashboardUpdateFailure(e, {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 18eec7303052..2307de9be1df 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2698,9 +2698,8 @@ export interface InsightModel<R extends Node<Record<string, any>> = Node<Record<
created_by: UserBasicType | null
is_sample: boolean
/**
- * @deprecated Write-only. Session responses omit it, so read membership with
- * `liveDashboardIds(insight.dashboard_tiles)`. Send it to place a new insight on dashboards, or to
- * replace a saved insight's whole membership.
+ * @deprecated Session responses omit it, so read membership with `liveDashboardIds(insight.dashboard_tiles)`.
+ * The app never sends it: on an unsaved insight it holds the dashboards to place the saved insight on.
*/
dashboards?: number[]
dashboard_tiles: DashboardTileBasicType[] | null
diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.ts
index b1a5b199fc05..6c3a20a7fe1a 100644
--- a/products/business_intelligence/frontend/biSceneLogic.ts
+++ b/products/business_intelligence/frontend/biSceneLogic.ts
@@ -22,6 +22,7 @@ import { accessLevelSatisfied, toAccessControlLevel } from 'lib/utils/accessCont
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -437,13 +438,12 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
return values.insight
}
const dashboard = Number(router.values.searchParams.dashboard)
+ const dashboardId =
+ !asCopy && !values.insight && Number.isInteger(dashboard) && dashboard > 0 ? dashboard : null
const payload = {
name: asCopy ? `${values.name.trim()} (copy)` : values.name.trim(),
query: JSON.parse(JSON.stringify(values.worksheet)) as BIVisualizationNodeApi,
saved: true,
- ...(!asCopy && !values.insight && Number.isInteger(dashboard) && dashboard > 0
- ? { dashboards: [dashboard] }
- : {}),
}
const state = { editorView: BIEditorView.BI, config: values.config }
const operation = values.insight && !asCopy ? 'update' : 'create'
@@ -451,16 +451,19 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType
values.insight && !asCopy
? await insightsPartialUpdate(String(values.currentTeamId), values.insight.id, payload)
: await insightsCreate(String(values.currentTeamId), payload)
+ if (dashboardId !== null) {
+ await insightsApi.addNewInsightToDashboards(insight.id, [dashboardId])
+ }
if (asCopy) {
cache.agentRefreshAfterSave = false
actions.setAgentUpdateState(null)
}
- captureBIEditorQuerySaved(state, 'insight', operation, !!payload.dashboards?.length)
+ captureBIEditorQuerySaved(state, 'insight', operation, dashboardId !== null)
captureBIWorksheetAction('saved', state.config, { insight_id: insight.id })
if (asCopy) {
captureBIWorksheetAction('copied', state.config, { insight_id: insight.id })
}
- if (payload.dashboards?.length) {
+ if (dashboardId !== null) {
captureBIWorksheetAction('added_to_dashboard', state.config, { insight_id: insight.id })
}
return insight
diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts
index 7be87736f96e..2a27b723539a 100644
--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts
+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.test.ts
@@ -90,7 +90,7 @@ describe('metricsStarterDashboardLogic', () => {
expect(mockInsightCreate).toHaveBeenCalledTimes(2)
const [countInsight, histogramInsight] = mockInsightCreate.mock.calls.map(([insight]) => insight)
- expect(countInsight.dashboards).toEqual([42])
+ expect(mockInsightCreate.mock.calls.map(([, dashboardIds]) => dashboardIds)).toEqual([[42], [42]])
expect(countInsight.query).toMatchObject({
kind: 'MetricsQuery',
clauses: [
diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
index e9ee1ad4628f..ea286fd0fca1 100644
--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
@@ -223,12 +223,7 @@ export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType
: {}),
}
const query: MetricsQuery = { kind: NodeKind.MetricsQuery, clauses: [clause] }
- await insightsApi.create({
- name: metricName,
- saved: true,
- dashboards: [dashboard.id],
- query,
- })
+ await insightsApi.create({ name: metricName, saved: true, query }, [dashboard.id])
created++
}
actions.createDashboardSuccess(dashboard)