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.

16.4 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'

import { ApiError } from 'lib/api-error'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { Breadcrumb } from '~/types'

import {
    metricsDashboardTemplatesAnalyzeCreate,
    metricsDashboardTemplatesApproveCreate,
    metricsDashboardTemplatesList,
    metricsDashboardTemplatesPreviewCreate,
    metricsDashboardTemplatesRegenerateCreate,
    metricsDashboardTemplatesRejectCreate,
    metricsDashboardTemplatesRetrieve,
} from 'products/metrics/frontend/generated/api'
import type {
    DashboardTemplateStatusEnumApi,
    MetricsDashboardTemplateApi,
} from 'products/metrics/frontend/generated/api.schemas'

export type ReviewStatusFilter = DashboardTemplateStatusEnumApi | 'all'

function errorDetail(error: unknown, fallback: string): string {
    return error instanceof ApiError && error.detail ? error.detail : fallback
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsDashboardReviewSceneLogicValues {
    currentTeamId: number | null // teamLogic
    analysisStarted: boolean
    analysisStartedLoading: boolean
    breadcrumbs: Breadcrumb[]
    previewDashboardId: number | null
    previewDashboardIdLoading: boolean
    previewError: string | null
    previewLoading: boolean
    previewRequestTemplateId: string | null
    regenerable: boolean
    reviewable: boolean
    statusFilter: ReviewStatusFilter
    template: MetricsDashboardTemplateApi | null
    templateId: string | null
    templateLoading: boolean
    templates: MetricsDashboardTemplateApi[] | null
    templatesLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsDashboardReviewSceneLogicActions {
    analyzeProject: () => any
    analyzeProjectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    analyzeProjectSuccess: (
        analysisStarted: boolean,
        payload?: any
    ) => {
        analysisStarted: boolean
        payload?: any
    }
    approveTemplate: () => any
    approveTemplateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    approveTemplateSuccess: (
        template: MetricsDashboardTemplateApi | null,
        payload?: any
    ) => {
        template: MetricsDashboardTemplateApi | null
        payload?: any
    }
    confirmRegenerate: () => {
        value: true
    }
    loadTemplate: () => any
    loadTemplateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTemplateSuccess: (
        template: MetricsDashboardTemplateApi | null,
        payload?: any
    ) => {
        template: MetricsDashboardTemplateApi | null
        payload?: any
    }
    loadTemplates: () => any
    loadTemplatesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTemplatesSuccess: (
        templates: MetricsDashboardTemplateApi[],
        payload?: any
    ) => {
        templates: MetricsDashboardTemplateApi[]
        payload?: any
    }
    openPreview: ({ templateId }: { templateId: string }) => {
        templateId: string
    }
    openPreviewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    openPreviewSuccess: (
        previewDashboardId: number | null,
        payload?: {
            templateId: string
        }
    ) => {
        previewDashboardId: number | null
        payload?: {
            templateId: string
        }
    }
    regenerateTemplate: () => any
    regenerateTemplateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    regenerateTemplateSuccess: (
        template: MetricsDashboardTemplateApi | null,
        payload?: any
    ) => {
        template: MetricsDashboardTemplateApi | null
        payload?: any
    }
    rejectTemplate: () => any
    rejectTemplateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    rejectTemplateSuccess: (
        template: MetricsDashboardTemplateApi | null,
        payload?: any
    ) => {
        template: MetricsDashboardTemplateApi | null
        payload?: any
    }
    setPreviewError: (previewError: string | null) => {
        previewError: string | null
    }
    setStatusFilter: (statusFilter: ReviewStatusFilter) => {
        statusFilter: ReviewStatusFilter
    }
    setTemplateId: (templateId: string | null) => {
        templateId: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsDashboardReviewSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        previewLoading: (previewRequestTemplateId: string | null, templateId: string | null) => boolean
        reviewable: (template: MetricsDashboardTemplateApi | null) => boolean
        regenerable: (template: MetricsDashboardTemplateApi | null) => boolean
        breadcrumbs: (template: MetricsDashboardTemplateApi | null, templateId: string | null) => Breadcrumb[]
    }
}

export type metricsDashboardReviewSceneLogicType = MakeLogicType<
    metricsDashboardReviewSceneLogicValues,
    metricsDashboardReviewSceneLogicActions,
    Record<string, any>,
    metricsDashboardReviewSceneLogicMeta
>

export const metricsDashboardReviewSceneLogic = kea<metricsDashboardReviewSceneLogicType>([
    path(['products', 'metrics', 'frontend', 'dashboardReview', 'metricsDashboardReviewSceneLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId']],
    })),
    actions({
        setStatusFilter: (statusFilter: ReviewStatusFilter) => ({ statusFilter }),
        setTemplateId: (templateId: string | null) => ({ templateId }),
        setPreviewError: (previewError: string | null) => ({ previewError }),
        confirmRegenerate: true,
    }),
    loaders(({ values }) => ({
        templates: [
            null as MetricsDashboardTemplateApi[] | null,
            {
                loadTemplates: async () =>
                    metricsDashboardTemplatesList(
                        String(values.currentTeamId),
                        values.statusFilter === 'all' ? {} : { status: values.statusFilter }
                    ),
            },
        ],
        template: [
            null as MetricsDashboardTemplateApi | null,
            {
                loadTemplate: async () =>
                    values.templateId
                        ? metricsDashboardTemplatesRetrieve(String(values.currentTeamId), values.templateId)
                        : null,
                approveTemplate: async () => {
                    try {
                        const template = await metricsDashboardTemplatesApproveCreate(
                            String(values.currentTeamId),
                            values.templateId as string
                        )
                        lemonToast.success(`Approved. Projects that send these metrics now see "${template.name}".`)
                        return template
                    } catch (error) {
                        lemonToast.error(errorDetail(error, 'Could not approve the dashboard.'))
                        return values.template
                    }
                },
                rejectTemplate: async () => {
                    try {
                        const template = await metricsDashboardTemplatesRejectCreate(
                            String(values.currentTeamId),
                            values.templateId as string
                        )
                        lemonToast.info(`Rejected "${template.name}".`)
                        return template
                    } catch (error) {
                        lemonToast.error(errorDetail(error, 'Could not reject the dashboard.'))
                        return values.template
                    }
                },
                regenerateTemplate: async () => {
                    try {
                        const template = await metricsDashboardTemplatesRegenerateCreate(
                            String(values.currentTeamId),
                            values.templateId as string
                        )
                        lemonToast.info(`Regenerating "${template.name}". It is back for review in a few minutes.`)
                        return template
                    } catch (error) {
                        lemonToast.error(errorDetail(error, 'Could not regenerate the dashboard.'))
                        // A failed start can still have reset the template and deleted its preview.
                        try {
                            return await metricsDashboardTemplatesRetrieve(
                                String(values.currentTeamId),
                                values.templateId as string
                            )
                        } catch {
                            return values.template
                        }
                    }
                },
            },
        ],
        analysisStarted: [
            false,
            {
                analyzeProject: async () => {
                    try {
                        await metricsDashboardTemplatesAnalyzeCreate(String(values.currentTeamId))
                        lemonToast.success('Analysis started. New dashboards appear here in a few minutes.')
                        return true
                    } catch (error) {
                        lemonToast.error(errorDetail(error, 'Could not start the analysis.'))
                        return false
                    }
                },
            },
        ],
        previewDashboardId: [
            null as number | null,
            {
                openPreview: async ({ templateId }: { templateId: string }) => {
                    try {
                        const { dashboard_id } = await metricsDashboardTemplatesPreviewCreate(
                            String(values.currentTeamId),
                            templateId
                        )
                        // The reviewer may have moved to another template while the preview was built.
                        return values.templateId === templateId ? dashboard_id : values.previewDashboardId
                    } catch (error) {
                        if (values.templateId !== templateId) {
                            return values.previewDashboardId
                        }
                        throw new Error(errorDetail(error, 'Could not build the preview dashboard.'))
                    }
                },
            },
        ],
    })),
    reducers({
        statusFilter: [
            'pending_review' as ReviewStatusFilter,
            {
                setStatusFilter: (_, { statusFilter }) => statusFilter,
            },
        ],
        templateId: [
            null as string | null,
            {
                setTemplateId: (_, { templateId }) => templateId,
            },
        ],
        template: {
            setTemplateId: () => null,
        },
        previewDashboardId: {
            setTemplateId: () => null,
            // A review deletes the preview, so the page stops showing it. A failed review keeps it.
            approveTemplateSuccess: (state, { template }) => (template?.status === 'approved' ? null : state),
            rejectTemplateSuccess: (state, { template }) => (template?.status === 'rejected' ? null : state),
            regenerateTemplateSuccess: (state, { template }) =>
                template && ['pending_review', 'rejected'].includes(template.status) ? state : null,
        },
        // The template of the preview request in flight. A stale request also ends the loader's own loading state.
        previewRequestTemplateId: [
            null as string | null,
            {
                openPreview: (_, { templateId }) => templateId,
                openPreviewSuccess: (state, { payload }) => (payload?.templateId === state ? null : state),
                openPreviewFailure: () => null,
                setTemplateId: () => null,
            },
        ],
        previewError: [
            null as string | null,
            {
                setPreviewError: (_, { previewError }) => previewError,
                setTemplateId: () => null,
                openPreview: () => null,
            },
        ],
    }),
    selectors({
        previewLoading: [
            (s) => [s.previewRequestTemplateId, s.templateId],
            (requestTemplateId: string | null, templateId: string | null): boolean =>
                requestTemplateId !== null && requestTemplateId === templateId,
        ],
        reviewable: [
            (s) => [s.template],
            (template: MetricsDashboardTemplateApi | null): boolean =>
                !!template && ['pending_review', 'rejected'].includes(template.status) && template.source !== 'curated',
        ],
        regenerable: [
            (s) => [s.template],
            (template: MetricsDashboardTemplateApi | null): boolean =>
                !!template &&
                template.source === 'generated' &&
                ['pending_review', 'rejected', 'failed'].includes(template.status),
        ],
        breadcrumbs: [
            (s) => [s.template, s.templateId],
            (template: MetricsDashboardTemplateApi | null, templateId: string | null): Breadcrumb[] => [
                { key: 'Metrics', name: 'Metrics', path: urls.metrics() },
                { key: 'MetricsDashboardReview', name: 'Dashboard review', path: urls.metricsDashboardReview() },
                ...(templateId
                    ? [
                          {
                              key: ['MetricsDashboardTemplate', templateId] as [string, string],
                              name: template?.name ?? 'Dashboard',
                          },
                      ]
                    : []),
            ],
        ],
    }),
    listeners(({ actions, values }) => ({
        setStatusFilter: () => {
            actions.loadTemplates()
        },
        setTemplateId: ({ templateId }) => {
            if (templateId) {
                actions.loadTemplate()
            } else {
                actions.loadTemplates()
            }
        },
        loadTemplateSuccess: () => {
            // Only a review deletes a preview, so a template that waits for no review gets none.
            if (values.reviewable && values.templateId) {
                actions.openPreview({ templateId: values.templateId })
            }
        },
        openPreviewFailure: ({ error }) => {
            actions.setPreviewError(error)
        },
        approveTemplateSuccess: () => {
            actions.loadTemplates()
        },
        confirmRegenerate: () => {
            LemonDialog.open({
                title: 'Regenerate this dashboard?',
                description: 'The new panels replace the current panels and preview.',
                primaryButton: {
                    children: 'Regenerate',
                    status: 'danger',
                    onClick: () => actions.regenerateTemplate(),
                },
                secondaryButton: { children: 'Cancel' },
            })
        },
        regenerateTemplateSuccess: () => {
            actions.loadTemplates()
        },
        rejectTemplateSuccess: ({ template }) => {
            actions.loadTemplates()
            // A rejected dashboard can still be approved, so it gets a new preview.
            if (template?.status === 'rejected' && values.templateId === template.id) {
                actions.openPreview({ templateId: template.id })
            }
        },
    })),
    urlToAction(({ actions, values }) => ({
        [urls.metricsDashboardReview(':templateId')]: ({ templateId }) => {
            if (templateId && templateId !== values.templateId) {
                actions.setTemplateId(templateId)
            }
        },
        [urls.metricsDashboardReview()]: () => {
            if (values.templateId !== null) {
                actions.setTemplateId(null)
            }
        },
    })),
    afterMount(({ actions, values }) => {
        if (!values.templateId) {
            actions.loadTemplates()
        }
    }),
])