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.

11.7 KB
Raw Blame
import posthog from 'posthog-js'
import { DashboardFilter, HogQLVariable } from 'src/queries/schema/schema-general'

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

import {
    describeDescriptionChange,
    describeTagChanges,
} from 'lib/components/ActivityLog/activityDescriptions/changeDescriptions'
import { describeChangeMappings } from 'lib/components/ActivityLog/activityDescriptions/describeChangeMappings'
import {
    ActivityChange,
    ActivityLogItem,
    ActivityLogSummary,
    ActivityLogUserName,
    ChangeMapping,
    Description,
    HumanizedChange,
    activityLogSummary,
    defaultDescriber,
    detectBoolean,
} from 'lib/components/ActivityLog/humanizeActivity'
import {
    BreakdownSummary,
    DateRangeSummary,
    PropertiesSummary,
    VariablesSummary,
} from 'lib/components/Cards/InsightCard/InsightDetails'
import { isKeyOf } from 'lib/utils/guards'
import { urls } from 'scenes/urls'

import { DashboardType } from '~/types'

import {
    DASHBOARD_GRID_COMPACTION_LABELS,
    DASHBOARD_TILE_SPACING_LABELS,
    TILE_GROUP_DISPLAY_LABELS,
} from './dashboardCustomization'

function nameAndLink(logItem?: ActivityLogItem): JSX.Element {
    return logItem?.item_id ? (
        <Link to={urls.dashboard(logItem.item_id)}>{logItem?.detail?.name || 'Unknown dashboard'}</Link>
    ) : logItem?.detail?.name ? (
        <>{logItem.detail.name}</>
    ) : (
        <i>Unknown dashboard</i>
    )
}

function dashboardSummary(logItem: ActivityLogItem, action: Description, preview?: string): ActivityLogSummary {
    return {
        actor: <ActivityLogUserName logItem={logItem} />,
        action,
        target: <>Dashboard · {nameAndLink(logItem)}</>,
        preview,
    }
}

const dashboardActionsMapping: Record<
    keyof DashboardType,
    (change?: ActivityChange, logItem?: ActivityLogItem, asNotification?: boolean) => ChangeMapping | null
> = {
    name: function onName(change, logItem, asNotification) {
        return {
            description: [
                <>
                    renamed {asNotification && 'the dashboard '}"{change?.before}" to{' '}
                    <strong>"{nameAndLink(logItem)}"</strong>
                </>,
            ],
            suffix: <></>,
            summary: [
                <>
                    renamed "{change?.before}" to "{change?.after}"
                </>,
            ],
        }
    },
    deleted: function onSoftDelete(change, logItem, asNotification) {
        const isDeleted = detectBoolean(change?.after)
        const describeChange = isDeleted ? 'deleted' : 'restored'
        return {
            description: [
                <>
                    {describeChange}
                    {asNotification && ' the dashboard '}
                </>,
            ],
            suffix: <>{nameAndLink(logItem)}</>,
            summary: [`${describeChange} the dashboard`],
        }
    },
    description: function onDescription(change, _, asNotification) {
        return describeDescriptionChange(change, asNotification, 'dashboard')
    },
    tags: describeTagChanges,
    pinned: function onPinned(change, logItem, asNotification) {
        const isFavoriteAfter = detectBoolean(change?.after)
        return {
            description: [
                <>
                    <div className="highlighted-activity">
                        {isFavoriteAfter ? '' : 'un-'}pinned{asNotification && ' the dashboard '}
                    </div>
                </>,
            ],
            suffix: <>{nameAndLink(logItem)}</>,
            summary: [isFavoriteAfter ? 'pinned the dashboard' : 'unpinned the dashboard'],
        }
    },
    filters: function onChangedFilters(change, logItem) {
        const filtersAfter = change?.after as DashboardFilter
        return {
            description: ['changed the dashboard filters'],
            extendedDescription: (
                <div className="ActivityDescription">
                    <PropertiesSummary properties={filtersAfter.properties} />
                    <BreakdownSummary breakdownFilter={filtersAfter.breakdown_filter} />
                    <DateRangeSummary dateFrom={filtersAfter.date_from} dateTo={filtersAfter.date_to} />
                </div>
            ),
            suffix: <>on the dashboard {nameAndLink(logItem)} to</>,
        }
    },
    variables: function onChangedVariables(change, logItem) {
        const variablesAfter = change?.after as Record<string, HogQLVariable>
        return {
            description: ['changed the dashboard variables'],
            extendedDescription: (
                <div className="ActivityDescription">
                    <VariablesSummary variables={variablesAfter} />
                </div>
            ),
            suffix: <>on the dashboard {nameAndLink(logItem)} to</>,
        }
    },
    id: () => null,
    created_at: () => null,
    created_by: () => null,
    persisted_filters: () => null,
    persisted_variables: () => null,
    breakdown_colors: () => null,
    data_color_theme_id: () => null,
    last_accessed_at: () => null,
    folder: () => null,
    file_system_id: () => null,
    file_system_path: () => null,
    is_shared: () => null,
    creation_mode: () => null,
    user_access_level: () => null,
    _highlight: () => null,
    last_refresh: () => null,
    tiles: () => null,
    last_viewed_at: () => null,
    quick_filter_ids: () => null,
    customization: function onChangedCustomization(change) {
        const before = change?.before as DashboardType['customization']
        const after = change?.after as DashboardType['customization']
        const description: Description[] = []
        if (after?.layout_compaction && after.layout_compaction !== before?.layout_compaction) {
            description.push(
                <>
                    changed tile movement to{' '}
                    <strong>{DASHBOARD_GRID_COMPACTION_LABELS[after.layout_compaction]}</strong>
                </>
            )
        }
        if (after?.tile_spacing && after.tile_spacing !== before?.tile_spacing) {
            if (description.length > 0) {
                description.push(' and ')
            }
            description.push(
                <>
                    changed tile density to <strong>{DASHBOARD_TILE_SPACING_LABELS[after.tile_spacing]}</strong>
                </>
            )
        }
        if (after?.group_display && after.group_display !== (before?.group_display ?? 'sections')) {
            if (description.length > 0) {
                description.push(' and ')
            }
            description.push(
                <>
                    changed how groups show to <strong>{TILE_GROUP_DISPLAY_LABELS[after.group_display]}</strong>
                </>
            )
        }
        return description.length > 0 ? { description } : null
    },
}

function describeSingleChange(
    change: ActivityChange | undefined,
    logItem: ActivityLogItem,
    asNotification: boolean | undefined
): ChangeMapping | null {
    // dashboard updates have to have a "field" to be described
    if (!change?.field || !isKeyOf(change.field, dashboardActionsMapping)) {
        return null
    }
    return dashboardActionsMapping[change.field](change, logItem, asNotification)
}

function describeUpdatedDashboard(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
    const mappings: ChangeMapping[] = []
    try {
        for (const change of logItem.detail.changes || []) {
            const processedChange = describeSingleChange(change, logItem, asNotification)
            if (processedChange) {
                mappings.push(processedChange)
            }
        }
    } catch (e) {
        console.error('Error while summarizing dashboard update', e)
        posthog.captureException(e)
    }

    return (
        describeChangeMappings(
            logItem,
            mappings,
            <>Dashboard · {nameAndLink(logItem)}</>,
            <>
                on {asNotification && ' the dashboard '}
                {nameAndLink(logItem)}
            </>
        ) ?? defaultDescriber(logItem, asNotification, nameAndLink(logItem))
    )
}

function describeShareLogin(logItem: ActivityLogItem, succeeded: boolean): HumanizedChange {
    const afterData = logItem.detail.changes?.[0]?.after as any
    const clientIp = afterData?.client_ip || 'unknown IP'

    if (succeeded) {
        const passwordNote = afterData?.password_note || 'unknown password'
        return {
            summary: activityLogSummary(
                logItem,
                'Authenticated to the shared dashboard',
                nameAndLink(logItem),
                `From ${clientIp}, using password ${passwordNote}`,
                <strong>Anonymous user</strong>
            ),
            description: (
                <>
                    <strong>Anonymous user</strong> successfully authenticated to shared dashboard{' '}
                    <b>{nameAndLink(logItem)}</b> from {clientIp} using password <strong>{passwordNote}</strong>
                </>
            ),
        }
    }
    return {
        summary: activityLogSummary(
            logItem,
            'Failed to authenticate to the shared dashboard',
            nameAndLink(logItem),
            `From ${clientIp}`,
            <strong>Anonymous user</strong>
        ),
        description: (
            <>
                <strong>Anonymous user</strong> failed to authenticate to shared dashboard <b>{nameAndLink(logItem)}</b>{' '}
                from {clientIp}
            </>
        ),
    }
}

const SHARING_SUMMARIES: Record<string, string> = {
    'sharing enabled': 'Shared the dashboard',
    'sharing disabled': 'Deleted the shared link',
    'access token refreshed': 'Refreshed the shared link',
}

const SHARING_SENTENCES: Record<string, string> = {
    'sharing enabled': 'shared',
    'sharing disabled': 'deleted shared link for',
    'access token refreshed': 'refreshed the shared link for',
}

const dashboardActivitySentences: Record<
    string,
    (logItem: ActivityLogItem, asNotification?: boolean) => HumanizedChange
> = {
    created: (logItem) => ({
        description: (
            <>
                <ActivityLogUserName logItem={logItem} /> created the dashboard {nameAndLink(logItem)}
            </>
        ),
        summary: dashboardSummary(logItem, 'Created the dashboard'),
    }),
    'sharing enabled': describeSharingActivity,
    'sharing disabled': describeSharingActivity,
    'access token refreshed': describeSharingActivity,
}

function describeSharingActivity(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
    const sentence = SHARING_SENTENCES[logItem.activity]
    const summary = SHARING_SUMMARIES[logItem.activity]
    return {
        description: (
            <>
                <ActivityLogUserName logItem={logItem} /> {sentence} {asNotification ? 'your' : 'the'} dashboard{' '}
                {nameAndLink(logItem)}
            </>
        ),
        summary: dashboardSummary(logItem, summary),
    }
}

export function dashboardActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {
    if (logItem.scope != 'Dashboard') {
        console.error('dashboard describer received a non-dashboard activity')
        return { description: null }
    }

    if (logItem.activity == 'updated') {
        return describeUpdatedDashboard(logItem, asNotification)
    }

    const sentenceDescriber = dashboardActivitySentences[logItem.activity]
    if (sentenceDescriber) {
        return sentenceDescriber(logItem, asNotification)
    }

    if (logItem.activity === 'share_login_success') {
        return describeShareLogin(logItem, true)
    }

    if (logItem.activity === 'share_login_failed') {
        return describeShareLogin(logItem, false)
    }

    return defaultDescriber(logItem, asNotification, nameAndLink(logItem))
}