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.

4.5 KB
Raw Blame
import { MakeLogicType, kea, path } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { PA_MESSAGE_FIELD_LIMITS, PAMessageField } from 'scenes/hog-functions/sub-templates/sub-templates'

import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'

import { PANotificationUseCase } from './productAnalyticsNotificationsLogic'

export type PANotificationExample = Record<PAMessageField, string>
export type PANotificationExamples = Partial<Record<PANotificationUseCase, PANotificationExample>>

// The most recent real event per use case, so a preview can show the project's own traffic instead
// of invented values. Time-bounded to keep it cheap (30 days is plenty: any project with
// autocapture on sees rageclicks far more often than that); the preview falls back to sample copy
// when a project has nothing (yet), so an empty result is normal, not an error.
const EXAMPLES_QUERY = `
SELECT
    'rageclick' AS use_case,
    argMax(coalesce(nullIf(toString(properties.$pathname), ''), toString(properties.$current_url)), timestamp) AS page,
    argMax(toString(properties.$browser), timestamp) AS browser
FROM events
WHERE timestamp >= now() - INTERVAL 30 DAY
  AND event = '$rageclick'
`

const KNOWN_USE_CASES: PANotificationUseCase[] = ['rageclick']

// Every field the message renders must be present, otherwise the "real" example would be a mix of
// the project's data and our invented copy — more misleading than an honest sample.
const REQUIRED_FIELDS: Record<PANotificationUseCase, PAMessageField[]> = {
    rageclick: ['page', 'browser'],
}

/** String columns arrive null when the property is missing — normalize those to an empty string. */
const asString = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')

// Array.from so a cut can't land inside a surrogate pair and render as a replacement character.
function truncateField(field: PAMessageField, value: string): string {
    const characters = Array.from(value)
    return characters.length > PA_MESSAGE_FIELD_LIMITS[field]
        ? characters.slice(0, PA_MESSAGE_FIELD_LIMITS[field]).join('')
        : value
}

export function parseExampleRows(rows: unknown[]): PANotificationExamples {
    const examples: PANotificationExamples = {}

    for (const row of rows) {
        const [rawUseCase, page, browser] = row as unknown[]
        const useCase = KNOWN_USE_CASES.find((candidate) => candidate === asString(rawUseCase))
        if (!useCase) {
            continue
        }

        const candidate: PANotificationExample = {
            page: asString(page),
            browser: asString(browser),
        }
        if (!REQUIRED_FIELDS[useCase].every((field) => candidate[field])) {
            continue
        }

        examples[useCase] = {
            page: truncateField('page', candidate.page),
            browser: truncateField('browser', candidate.browser),
        }
    }

    return examples
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productAnalyticsNotificationExamplesLogicValues {
    examples: PANotificationExamples
    examplesLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface productAnalyticsNotificationExamplesLogicActions {
    loadExamples: () => any
    loadExamplesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadExamplesSuccess: (
        examples: Partial<Record<'rageclick', PANotificationExample>>,
        payload?: any
    ) => {
        examples: Partial<Record<'rageclick', PANotificationExample>>
        payload?: any
    }
}

export type productAnalyticsNotificationExamplesLogicType = MakeLogicType<
    productAnalyticsNotificationExamplesLogicValues,
    productAnalyticsNotificationExamplesLogicActions
>

export const productAnalyticsNotificationExamplesLogic = kea<productAnalyticsNotificationExamplesLogicType>([
    path(['products', 'product_analytics', 'frontend', 'notifications', 'productAnalyticsNotificationExamplesLogic']),
    loaders({
        examples: [
            {} as PANotificationExamples,
            {
                loadExamples: async (): Promise<PANotificationExamples> => {
                    const response = (await api.query({
                        kind: NodeKind.HogQLQuery,
                        query: EXAMPLES_QUERY,
                    })) as HogQLQueryResponse
                    return parseExampleRows(response?.results ?? [])
                },
            },
        ],
    }),
])