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.

6.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'

import {
    columnsForSavedView,
    DEFAULT_LOGS_COLUMNS,
    LogsColumnConfig,
} from 'products/logs/frontend/components/LogsViewer/config/columns'
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { LogsViewApi, LogsViewApiFilters } from 'products/logs/frontend/generated/api.schemas'
import { DEFAULT_ACTIVE_TAB, logsSceneLogic } from 'products/logs/frontend/logsSceneLogic'

import type { LogsSceneActiveTab } from '../../logsSceneLogic'
import type { LogsViewerFilters } from '../LogsViewer/config/types'

export type LogsView = LogsViewApi

export interface LogsViewsLogicProps {
    id: string
}

const logsViewsUrl = (teamId: number | null): string => `api/projects/${teamId}/logs/views`

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewsLogicValues {
    currentTeamId: number | null // teamLogic
    views: LogsView[]
    viewsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewsLogicActions {
    setActiveTab: (activeTab: LogsSceneActiveTab) => {
        activeTab: LogsSceneActiveTab
    } // logsSceneLogic
    setColumns: (columns: LogsColumnConfig[]) => {
        columns: LogsColumnConfig[]
    } // logsViewerConfigLogic
    setFilters: (
        filters: Partial<LogsViewerFilters>,
        pushToHistory?: boolean | undefined
    ) => {
        filters: Partial<LogsViewerFilters>
        pushToHistory: boolean
    } // logsViewerFiltersLogic
    createView: ({
        name,
        filters,
        columns,
    }: {
        columns: LogsColumnConfig[]
        filters: LogsViewApiFilters
        name: string
    }) => {
        name: string
        filters: LogsViewApiFilters
        columns: LogsColumnConfig[]
    }
    createViewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createViewSuccess: (
        views: LogsViewApi[],
        payload?: {
            name: string
            filters: LogsViewApiFilters
            columns: LogsColumnConfig[]
        }
    ) => {
        views: LogsViewApi[]
        payload?: {
            name: string
            filters: LogsViewApiFilters
            columns: LogsColumnConfig[]
        }
    }
    deleteView: (shortId: string) => {
        shortId: string
    }
    loadView: (view: LogsView) => {
        view: LogsViewApi
    }
    loadViews: () => any
    loadViewsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadViewsSuccess: (
        views: LogsView[],
        payload?: any
    ) => {
        views: LogsView[]
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewsLogicMeta {
    key: string
}

export type logsViewsLogicType = MakeLogicType<
    logsViewsLogicValues,
    logsViewsLogicActions,
    LogsViewsLogicProps,
    logsViewsLogicMeta
>

export const logsViewsLogic = kea<logsViewsLogicType>([
    props({} as LogsViewsLogicProps),
    key((props) => props.id),
    path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViews', 'logsViewsLogic', key]),

    connect((props: LogsViewsLogicProps) => ({
        values: [teamLogic, ['currentTeamId']],
        actions: [
            logsViewerFiltersLogic({ id: props.id }),
            ['setFilters'],
            logsViewerConfigLogic({ id: props.id }),
            ['setColumns'],
            logsSceneLogic(),
            ['setActiveTab'],
        ],
    })),

    actions({
        deleteView: (shortId: string) => ({ shortId }),
        loadView: (view: LogsView) => ({ view }),
    }),

    loaders(({ values }) => ({
        views: [
            [] as LogsView[],
            {
                loadViews: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                    const response = await api.get(`${logsViewsUrl(values.currentTeamId)}/`)
                    return response.results
                },
                createView: async ({
                    name,
                    filters,
                    columns,
                }: {
                    name: string
                    filters: LogsViewApiFilters
                    columns: LogsColumnConfig[]
                }) => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                    const created: LogsView = await api.create(`${logsViewsUrl(values.currentTeamId)}/`, {
                        name,
                        filters,
                        columns: columnsForSavedView(columns),
                    })
                    lemonToast.success('View saved')
                    return [created, ...values.views]
                },
            },
        ],
    })),

    reducers({
        views: {
            deleteView: (state, { shortId }) => state.filter((v) => v.short_id !== shortId),
        },
    }),

    listeners(({ actions, values }) => ({
        deleteView: async ({ shortId }) => {
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                await api.delete(`${logsViewsUrl(values.currentTeamId)}/${shortId}/`)
                lemonToast.success('View deleted')
            } catch {
                lemonToast.error('Failed to delete view')
                actions.loadViews()
            }
        },
        loadView: ({ view }) => {
            // A null `columns` means the view has no column preference, so it opens with the default set
            actions.setColumns(view.columns ?? DEFAULT_LOGS_COLUMNS)
            actions.setFilters(view.filters || {})
            actions.setActiveTab(DEFAULT_ACTIVE_TAB)
        },
        createViewFailure: () => {
            lemonToast.error('Failed to save view')
        },
        loadViewsFailure: () => {
            lemonToast.error('Failed to load saved views')
        },
    })),
])