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.

13.6 KB
Raw Blame
import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'

import { expectLogic } from 'kea-test-utils'

import { teamLogic } from 'scenes/teamLogic'

import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { AccessControlLevel, DashboardBasicType } from '~/types'

import * as generatedApi from 'products/dashboards/frontend/generated/api'
import type { DashboardBulkDeleteResponseApi } from 'products/dashboards/frontend/generated/api.schemas'

import { dashboardsModel, mergeTileTextUpdatesIntoDashboard, nameCompareFunction } from './dashboardsModel'

const dashboards: Partial<DashboardBasicType>[] = [
    {
        id: 1,
        name: 'Generated Dashboard: 123',
    },
    {
        id: 2,
        name: 'Generated Dashboard: 456',
    },
    {
        id: 3,
        name: 'Dashboard: 789',
    },
    {
        id: 4,
        name: 'Generated Dashboard: 101',
    },
    {
        id: 5,
        name: 'Dashboard: 112',
    },
    {
        id: 6,
        name: 'Dashboard: 131',
    },
    {
        id: 7,
    },
    {
        id: 8,
        name: 'k',
    },
    {
        id: 9,
        name: 'Pinned Later',
        pinned: true,
        last_viewed_at: '2024-05-02T12:00:00Z',
    },
    {
        id: 10,
        name: 'Pinned Never',
        pinned: true,
        last_viewed_at: null,
    },
    {
        id: 11,
        name: 'Pinned Earlier',
        pinned: true,
        last_viewed_at: '2024-04-30T12:00:00Z',
    },
]

const basicDashboard: DashboardBasicType = {
    id: 1,
    name: '',
    description: 'This is not a generated dashboard',
    pinned: false,
    created_at: new Date().toISOString(),
    created_by: null,
    last_accessed_at: null,
    last_viewed_at: null,
    is_shared: false,
    deleted: false,
    creation_mode: 'default',
    user_access_level: AccessControlLevel.Editor,
}

describe('the dashboards model', () => {
    let logic: ReturnType<typeof dashboardsModel.build>

    beforeEach(async () => {
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': () => {
                    return [
                        200,
                        {
                            count: dashboards.length,
                            results: dashboards,
                            next: undefined,
                        },
                    ]
                },
            },
        })

        initKeaTests()
        logic = dashboardsModel()
        logic.mount()
    })

    it('does not load dashboards until a consumer requests them', () => {
        expect(logic.values.pagedDashboards).toBeNull()
        expect(logic.values.pagedDashboardsLoading).toBe(false)
    })

    it('loads dashboards when a consumer requests them', async () => {
        await expectLogic(logic, () => {
            logic.actions.loadDashboardsIfNeeded()
        }).toDispatchActions(['loadDashboardsSuccess'])
    })

    it('reloads every page after a failed bulk deletion', async () => {
        await expectLogic(logic, () => logic.actions.loadDashboards()).toDispatchActions(['loadDashboardsSuccess'])
        let failRequest: (error: Error) => void
        const request = new Promise<DashboardBulkDeleteResponseApi>((_, reject) => {
            failRequest = reject
        })
        const deleteSpy = jest.spyOn(generatedApi, 'dashboardsBulkDeleteCreate').mockReturnValueOnce(request)
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': ({ request }) => {
                    const offset = new URL(request.url).searchParams.get('offset')
                    return [
                        200,
                        {
                            count: 2,
                            results: [{ ...basicDashboard, id: offset === '0' ? 5 : 6 }],
                            next: offset === '0' ? '/api/projects/1/dashboards/?offset=1' : null,
                            previous: null,
                        },
                    ]
                },
            },
        })
        try {
            logic.actions.bulkDeleteDashboards({ ids: [3], onStillSelected: jest.fn() })
            await expectLogic(logic, () => failRequest!(new Error('Lost response'))).toDispatchActions([
                'bulkDeleteDashboardsFailure',
                'reloadDashboardsSuccess',
            ])
            expect(Object.keys(logic.values.rawDashboards).sort()).toEqual(['5', '6'])
            expect(logic.values.pagingDashboardsCompleted).toBe(true)
        } finally {
            deleteSpy.mockRestore()
        }
    })

    describe('sorting dashboards', () => {
        it('can sort dashboards correctly', async () => {
            await expectLogic(logic, () => {
                logic.actions.loadDashboards()
            })
                .toDispatchActions(['loadDashboardsSuccess'])
                .toMatchValues({
                    nameSortedDashboards: [
                        {
                            id: 11,
                            last_viewed_at: '2024-04-30T12:00:00Z',
                            name: 'Pinned Earlier',
                            pinned: true,
                        },
                        {
                            id: 9,
                            last_viewed_at: '2024-05-02T12:00:00Z',
                            name: 'Pinned Later',
                            pinned: true,
                        },
                        {
                            id: 10,
                            last_viewed_at: null,
                            name: 'Pinned Never',
                            pinned: true,
                        },
                        {
                            id: 5,
                            name: 'Dashboard: 112',
                        },
                        {
                            id: 6,
                            name: 'Dashboard: 131',
                        },
                        {
                            id: 3,
                            name: 'Dashboard: 789',
                        },
                        {
                            id: 8,
                            name: 'k',
                        },
                        {
                            id: 7,
                        },
                    ],
                })
        })

        it('compares names correctly', async () => {
            const generatedDashboardA = { ...basicDashboard, id: 1, name: 'Generated Dashboard: XYZ' }
            const untitledDashboard = { ...basicDashboard, id: 2, name: 'Untitled' }
            const randomDashboard = { ...basicDashboard, id: 3, name: 'Random' }
            const randomDashboard2 = { ...basicDashboard, id: 3, name: 'Too Random' }
            expect(nameCompareFunction(generatedDashboardA, untitledDashboard)).toEqual(-1)
            expect(nameCompareFunction(untitledDashboard, generatedDashboardA)).toEqual(1)
            expect(nameCompareFunction(generatedDashboardA, randomDashboard)).toEqual(-1)
            expect(nameCompareFunction(randomDashboard, generatedDashboardA)).toEqual(1)
            expect(nameCompareFunction(generatedDashboardA, randomDashboard2)).toEqual(-1)
            expect(nameCompareFunction(randomDashboard2, generatedDashboardA)).toEqual(1)

            expect(nameCompareFunction(untitledDashboard, randomDashboard)).toEqual(1)
            expect(nameCompareFunction(randomDashboard, untitledDashboard)).toEqual(-1)
            expect(nameCompareFunction(untitledDashboard, randomDashboard2)).toEqual(1)
            expect(nameCompareFunction(randomDashboard2, untitledDashboard)).toEqual(-1)

            expect(nameCompareFunction(randomDashboard2, randomDashboard)).toEqual(1)
            expect(nameCompareFunction(randomDashboard, randomDashboard2)).toEqual(-1)
        })

        it('sorts pinned dashboards by last viewed time', async () => {
            await expectLogic(logic, () => {
                logic.actions.loadDashboards()
            })
                .toDispatchActions(['loadDashboardsSuccess'])
                .toMatchValues({
                    pinnedDashboards: [
                        expect.objectContaining({ id: 9 }),
                        expect.objectContaining({ id: 11 }),
                        expect.objectContaining({ id: 10 }),
                    ],
                })
        })
    })

    describe('updating folders after a move', () => {
        beforeEach(async () => {
            await expectLogic(logic, () => logic.actions.loadDashboards()).toFinishAllListeners()
        })

        it('files a dashboard at its new path, and derives the folder from it', async () => {
            logic.actions.patchDashboardFolders({ 1: 'Revenue/Q3/Growth', 2: 'At the root' })
            expect(logic.values.rawDashboards[1].file_system_path).toEqual('Revenue/Q3/Growth')
            expect(logic.values.rawDashboards[1].folder).toEqual('Revenue/Q3')
            // A dashboard at the project root has no folder above it
            expect(logic.values.rawDashboards[2].folder).toEqual('')
        })

        it('ignores ids it does not hold', async () => {
            const before = logic.values.rawDashboards
            logic.actions.patchDashboardFolders({ 99999: 'Revenue/Missing' })
            expect(logic.values.rawDashboards).toBe(before)
        })

        it('re-parents everything under a moved folder, sparing similarly named siblings', async () => {
            logic.actions.patchDashboardFolders({
                1: 'Revenue/One',
                2: 'Revenue/Q3/Two',
                3: 'Revenue archive/Three',
            })
            logic.actions.reparentDashboardFolders('Revenue', 'Finance/Revenue')
            expect(logic.values.rawDashboards[1].folder).toEqual('Finance/Revenue')
            expect(logic.values.rawDashboards[2].folder).toEqual('Finance/Revenue/Q3')
            // 'Revenue archive' merely starts with the moved folder's name, so it stays put
            expect(logic.values.rawDashboards[3].folder).toEqual('Revenue archive')
        })

        it('keeps the path in step with the folder, so a second move starts from the right place', async () => {
            logic.actions.patchDashboardFolders({ 1: 'Revenue/Growth' })
            logic.actions.reparentDashboardFolders('Revenue', 'Finance/Revenue')
            expect(logic.values.rawDashboards[1].file_system_path).toEqual('Finance/Revenue/Growth')
        })

        it('leaves the map alone when nothing sits under the moved folder', async () => {
            const before = logic.values.rawDashboards
            logic.actions.reparentDashboardFolders('Nowhere', 'Elsewhere')
            expect(logic.values.rawDashboards).toBe(before)
        })
    })

    it('clears primary_dashboard from team when deleting the primary dashboard', async () => {
        const primaryDashboardId = 42
        initKeaTests(true, { ...MOCK_DEFAULT_TEAM, primary_dashboard: primaryDashboardId })
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': {
                    count: 0,
                    results: [],
                },
            },
            patch: {
                '/api/environments/:team_id/dashboards/:id/': {
                    id: primaryDashboardId,
                    name: 'My Dashboard',
                    deleted: true,
                },
            },
        })
        logic = dashboardsModel()
        logic.mount()

        logic.actions.deleteDashboard({ id: primaryDashboardId, deleteInsights: false })

        await expectLogic(logic).toDispatchActions(['deleteDashboardSuccess'])
        await expectLogic(teamLogic).toMatchValues({
            currentTeam: expect.objectContaining({ primary_dashboard: null }),
        })
    })

    it('does not clear primary_dashboard when deleting a non-primary dashboard', async () => {
        const primaryDashboardId = 42
        initKeaTests(true, { ...MOCK_DEFAULT_TEAM, primary_dashboard: primaryDashboardId })
        useMocks({
            get: {
                '/api/environments/:team_id/dashboards/': {
                    count: 0,
                    results: [],
                },
            },
            patch: {
                '/api/environments/:team_id/dashboards/:id/': {
                    id: 99,
                    name: 'Other Dashboard',
                    deleted: true,
                },
            },
        })
        logic = dashboardsModel()
        logic.mount()

        logic.actions.deleteDashboard({ id: 99, deleteInsights: false })

        await expectLogic(logic).toDispatchActions(['deleteDashboardSuccess'])
        await expectLogic(teamLogic).toMatchValues({
            currentTeam: expect.objectContaining({ primary_dashboard: primaryDashboardId }),
        })
    })
})

describe('mergeTileTextUpdatesIntoDashboard', () => {
    it('updates editable text fields and preserves server metadata', () => {
        const dashboard = {
            id: 123,
            tiles: [
                {
                    id: 1,
                    text: {
                        body: 'server body',
                        agent_context: 'server context',
                        last_modified_at: '2026-03-17T10:00:00Z',
                    },
                },
            ],
        } as any

        const merged = mergeTileTextUpdatesIntoDashboard(dashboard, [
            {
                id: 1,
                text: {
                    body: 'client body',
                    agent_context: 'client context',
                    last_modified_at: 'stale-client-value',
                },
            },
        ])

        expect(merged.tiles?.[0]?.text?.body).toEqual('client body')
        expect(merged.tiles?.[0]?.text?.agent_context).toEqual('client context')
        expect(merged.tiles?.[0]?.text?.last_modified_at).toEqual('2026-03-17T10:00:00Z')
    })
})