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.

23.5 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { isPersonPropertyFilter, parseProperties } from 'lib/components/PropertyFilters/utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { groupBy } from 'lib/utils/arrays'
import { parseDateInTimezone } from 'lib/utils/datetime'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { teamLogic } from 'scenes/teamLogic'

import { AnnotationDataWithoutInsight, annotationsModel, deserializeAnnotation } from '~/models/annotationsModel'
import { BreakdownFilter } from '~/queries/schema/schema-general'
import {
    AnnotationScope,
    AnnotationType,
    AnyPropertyFilter,
    DashboardType,
    DatedAnnotationType,
    InsightLogicProps,
    InsightSourceProject,
    IntervalType,
    PropertyGroupFilter,
    InsightModel,
} from '~/types'

import type { AnnotationData } from '../../../models/annotationsModel'
import type { Node } from '../../../queries/schema/schema-general'
import type { RawAnnotationType } from '../../../types'
import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
import { projectAnnotationsLogic } from './projectAnnotationsLogic'

export interface AnnotationsOverlayLogicProps extends Omit<InsightLogicProps, 'dashboardId'> {
    dashboardId: DashboardType['id'] | undefined
    insightNumericId: InsightModel['id'] | 'new'
    dates: string[]
    ticks: { value: number }[]
    /** Disambiguator for charts that mount more than one overlay against the same insight
     *  (e.g. compare-against-previous renders one layer per period). Without it, both layers
     *  would share the same kea instance and the second mount's `dates`/`ticks` would
     *  overwrite the first. */
    kind?: string
    // Charts without an insight query, like SQL charts, pass the scope in. Unset reads it from the insight.
    annotationsScope?: AnnotationScope | null
}

/** Week/month charts bucket annotations by day so distinct dates don't collapse into one badge. */
export function getGroupingUnit(intervalUnit: IntervalType): IntervalType {
    return ['week', 'month', 'quarter', 'year'].includes(intervalUnit) ? 'day' : intervalUnit
}

export function determineAnnotationsDateGroup(date: Dayjs, intervalUnit: IntervalType): string {
    return date.startOf(getGroupingUnit(intervalUnit)).format('YYYY-MM-DD HH:mm:ssZZ')
}

function hasPersonPropertyFiltersOrBreakdown(
    properties: AnyPropertyFilter[] | PropertyGroupFilter | null | undefined,
    breakdownFilter: BreakdownFilter | null | undefined
): boolean {
    // Check if there are person property filters
    if (properties) {
        const parsedProperties = parseProperties(properties)
        if (parsedProperties.some((prop) => isPersonPropertyFilter(prop))) {
            return true
        }
    }

    // Check if breakdown is by person property
    if (breakdownFilter) {
        if (breakdownFilter.breakdown_type === 'person') {
            return true
        }
        if (breakdownFilter.breakdowns?.some((breakdown) => breakdown.type === 'person')) {
            return true
        }
    }

    return false
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsOverlayLogicValues {
    currentProjectAnnotationsLoading: boolean // annotationsModel
    currentProjectRawAnnotations: RawAnnotationType[] // annotationsModel
    featureFlags: FeatureFlagsSet // featureFlagLogic
    insightId: number | null // insightLogic
    savedInsight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogic
    annotationsScope: AnnotationScope | null | undefined // insightVizDataLogic
    breakdownFilter: BreakdownFilter | null | undefined // insightVizDataLogic
    interval: IntervalType | null | undefined // insightVizDataLogic
    properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined // insightVizDataLogic
    sourceProjectAnnotationsLoading: boolean // projectAnnotationsLogic
    sourceProjectRawAnnotations: RawAnnotationType[] // projectAnnotationsLogic
    currentProjectTimezone: string // teamLogic
    activeDate: Dayjs | null
    annotationBadgeDataIndices: Array<{
        dataIndex: number
        date: Dayjs
        dateKey: string
    }>
    annotations: AnnotationType[]
    annotationsLoading: boolean
    annotationsOverlayProps: AnnotationsOverlayLogicProps
    dateRange: [Dayjs, Dayjs] | null
    groupedAnnotations: Record<number | string, DatedAnnotationType[]>
    groupingUnit: IntervalType
    intervalUnit: IntervalType
    isDateLocked: boolean
    isPopoverShown: boolean
    readOnly: boolean
    relevantAnnotations: DatedAnnotationType[]
    tickDates: Dayjs[]
    tickPositions: number[]
    timezone: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsOverlayLogicActions {
    createAnnotationGenerically: (annotationData: AnnotationData) => AnnotationData // annotationsModel
    deleteAnnotation: (annotation: AnnotationType) => {
        annotation: AnnotationType
    } // annotationsModel
    updateAnnotation: (args_0: {
        annotationData: AnnotationDataWithoutInsight
        annotationId: RawAnnotationType['id']
    }) => {
        annotationData: AnnotationDataWithoutInsight
        annotationId: RawAnnotationType[]
    } // annotationsModel
    activateDate: (date: Dayjs) => {
        date: Dayjs
    }
    closePopover: () => {
        value: true
    }
    createAnnotation: (annotationData: AnnotationDataWithoutInsight) => {
        annotationData: AnnotationDataWithoutInsight
    }
    deactivateDate: () => {
        value: true
    }
    lockDate: () => {
        value: true
    }
    unlockDate: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsOverlayLogicMeta {
    key: number | string
    __keaTypeGenInternalSelectorTypes: {
        annotationsOverlayProps: (arg: any) => AnnotationsOverlayLogicProps
        readOnly: (arg: InsightSourceProject | undefined) => boolean
        timezone: (currentProjectTimezone: string, arg: InsightSourceProject | undefined) => string
        annotations: (
            currentProjectRawAnnotations: RawAnnotationType[],
            sourceProjectRawAnnotations: RawAnnotationType[],
            timezone: string,
            arg: InsightSourceProject | undefined
        ) => AnnotationType[]
        annotationsLoading: (
            currentProjectAnnotationsLoading: boolean,
            sourceProjectAnnotationsLoading: boolean,
            arg: InsightSourceProject | undefined
        ) => boolean
        intervalUnit: (interval: IntervalType | null | undefined) => IntervalType
        groupingUnit: (intervalUnit: IntervalType) => IntervalType
        tickPositions: (
            ticks: {
                value: number
            }[]
        ) => number[]
        tickDates: (timezone: string, arg: string[], tickPositions: number[]) => Dayjs[]
        dateRange: (timezone: string, arg: string[], intervalUnit: IntervalType) => [Dayjs, Dayjs] | null
        relevantAnnotations: (
            annotations: AnnotationType[],
            dateRange: [Dayjs, Dayjs] | null,
            timezone: string,
            featureFlags: FeatureFlagsSet,
            insightNumericId: number | 'new',
            dashboardId: number | undefined,
            savedInsight: Partial<InsightModel<Node<Record<string, any>>>>,
            properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined,
            breakdownFilter: BreakdownFilter | null | undefined,
            annotationsScope: AnnotationScope | null | undefined,
            arg: AnnotationScope | null | undefined
        ) => DatedAnnotationType[]
        groupedAnnotations: (
            relevantAnnotations: DatedAnnotationType[],
            intervalUnit: IntervalType
        ) => Record<number | string, DatedAnnotationType[]>
        annotationBadgeDataIndices: (
            groupedAnnotations: Record<number | string, DatedAnnotationType[]>,
            intervalUnit: IntervalType,
            timezone: string,
            arg: string[]
        ) => Array<{
            dataIndex: number
            date: Dayjs
            dateKey: string
        }>
    }
}

export type annotationsOverlayLogicType = MakeLogicType<
    annotationsOverlayLogicValues,
    annotationsOverlayLogicActions,
    AnnotationsOverlayLogicProps,
    annotationsOverlayLogicMeta
>

export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([
    path((key) => ['lib', 'components', 'Annotations', 'annotationsOverlayLogic', key]),
    props({ dashboardId: undefined, sourceProject: undefined } as AnnotationsOverlayLogicProps),
    key(({ insightNumericId, kind, sourceProject }) => {
        const key = kind ? `${insightNumericId}::${kind}` : insightNumericId
        // The connected annotation source is fixed when the logic is built, and one insight can show in its own
        // project and on a cross-project dashboard at once, in two scene tabs.
        return sourceProject ? `${key}@${sourceProject.id}` : key
    }),
    connect((props: AnnotationsOverlayLogicProps) => ({
        values: [
            insightLogic,
            ['insightId', 'savedInsight'],
            insightVizDataLogic,
            ['interval', 'properties', 'breakdownFilter', 'annotationsScope'],
            annotationsModel,
            [
                'rawAnnotations as currentProjectRawAnnotations',
                'rawAnnotationsLoading as currentProjectAnnotationsLoading',
            ],
            projectAnnotationsLogic({ projectId: props.sourceProject?.id ?? null }),
            [
                'rawAnnotations as sourceProjectRawAnnotations',
                'rawAnnotationsLoading as sourceProjectAnnotationsLoading',
            ],
            teamLogic,
            ['timezone as currentProjectTimezone'],
            featureFlagLogic,
            ['featureFlags'],
        ],
        actions: [annotationsModel, ['createAnnotationGenerically', 'updateAnnotation', 'deleteAnnotation']],
    })),
    actions({
        createAnnotation: (annotationData: AnnotationDataWithoutInsight) => ({ annotationData }),
        activateDate: (date: Dayjs) => ({ date }),
        deactivateDate: true,
        lockDate: true,
        unlockDate: true,
        closePopover: true,
    }),
    reducers({
        isPopoverShown: [
            false,
            {
                activateDate: () => true,
                deactivateDate: () => false,
                closePopover: () => false,
            },
        ],
        activeDate: [
            null as Dayjs | null,
            {
                activateDate: (_, { date }) => date,
                deactivateDate: () => null,
                closePopover: () => null,
            },
        ],
        isDateLocked: [
            false,
            {
                lockDate: () => true,
                unlockDate: () => false,
                closePopover: () => false,
            },
        ],
    }),
    listeners(({ actions, props, values }) => ({
        createAnnotation: async ({ annotationData }) => {
            if (values.readOnly) {
                return
            }
            const insightNumericId = props.insightNumericId !== 'new' ? props.insightNumericId : null
            actions.createAnnotationGenerically({ ...annotationData, dashboard_item: insightNumericId })
        },
    })),
    selectors({
        annotationsOverlayProps: [
            () => [(_, props) => props],
            (props: AnnotationsOverlayLogicProps): AnnotationsOverlayLogicProps => props,
        ],
        // Annotations are created and edited through the current project's endpoints, which would
        // file them under the wrong project or miss them.
        readOnly: [
            () => [(_, props: AnnotationsOverlayLogicProps) => props.sourceProject],
            (sourceProject: InsightSourceProject | undefined): boolean => !!sourceProject,
        ],
        timezone: [
            (s) => [s.currentProjectTimezone, (_, props: AnnotationsOverlayLogicProps) => props.sourceProject],
            (currentProjectTimezone: string, sourceProject: InsightSourceProject | undefined): string =>
                sourceProject?.timezone ?? currentProjectTimezone,
        ],
        annotations: [
            (s) => [
                s.currentProjectRawAnnotations,
                s.sourceProjectRawAnnotations,
                s.timezone,
                (_, props: AnnotationsOverlayLogicProps) => props.sourceProject,
            ],
            (
                currentProjectRawAnnotations: RawAnnotationType[],
                sourceProjectRawAnnotations: RawAnnotationType[],
                timezone: string,
                sourceProject: InsightSourceProject | undefined
            ): AnnotationType[] =>
                (sourceProject ? sourceProjectRawAnnotations : currentProjectRawAnnotations).map((annotation) =>
                    deserializeAnnotation(annotation, timezone)
                ),
        ],
        annotationsLoading: [
            (s) => [
                s.currentProjectAnnotationsLoading,
                s.sourceProjectAnnotationsLoading,
                (_, props: AnnotationsOverlayLogicProps) => props.sourceProject,
            ],
            (
                currentProjectAnnotationsLoading: boolean,
                sourceProjectAnnotationsLoading: boolean,
                sourceProject: InsightSourceProject | undefined
            ): boolean => (sourceProject ? sourceProjectAnnotationsLoading : currentProjectAnnotationsLoading),
        ],
        intervalUnit: [(s) => [s.interval], (interval: IntervalType | null | undefined) => interval || 'day'],
        groupingUnit: [
            (s) => [s.intervalUnit],
            (intervalUnit: IntervalType): IntervalType => getGroupingUnit(intervalUnit),
        ],
        tickPositions: [
            (_, p) => [p.ticks],
            (
                ticks: {
                    value: number
                }[]
            ): number[] => ticks.map(({ value }) => value),
        ],
        tickDates: [
            (s) => [s.timezone, (_, props: AnnotationsOverlayLogicProps) => props.dates, s.tickPositions],
            (timezone: string, dates: string[], tickPositions: number[]): Dayjs[] =>
                tickPositions.map((dateIndex) => parseDateInTimezone(dates[dateIndex], timezone)),
        ],
        dateRange: [
            (s) => [s.timezone, (_, props: AnnotationsOverlayLogicProps) => props.dates, s.intervalUnit],
            (timezone: string, dates: string[], intervalUnit: IntervalType): [Dayjs, Dayjs] | null => {
                if (dates.length === 0) {
                    return null
                }
                const first = parseDateInTimezone(dates[0], timezone)
                const last = parseDateInTimezone(dates[dates.length - 1], timezone).add(1, intervalUnit)
                return [first, last]
            },
        ],
        relevantAnnotations: [
            (s, p) => [
                s.annotations,
                s.dateRange,
                s.timezone,
                s.featureFlags,
                p.insightNumericId,
                p.dashboardId,
                s.savedInsight,
                s.properties,
                s.breakdownFilter,
                s.annotationsScope,
                (_, props: AnnotationsOverlayLogicProps) => props.annotationsScope,
            ],
            (
                annotations: AnnotationType[],
                dateRange: [Dayjs, Dayjs] | null,
                timezone: string,
                featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
                insightNumericId: number | 'new',
                dashboardId: number | undefined,
                savedInsight: Partial<
                    InsightModel<import('~/queries/schema/schema-general').Node<Record<string, any>>>
                >,
                properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined,
                breakdownFilter: BreakdownFilter | null | undefined,
                insightAnnotationsScope: AnnotationScope | null | undefined,
                annotationsScopeOverride: AnnotationScope | null | undefined
            ) => {
                const annotationsScope = annotationsScopeOverride ?? insightAnnotationsScope
                // This assumes that there are no more annotations in the project than AnnotationsViewSet
                // pagination class's default_limit of 100. As of June 2023, this is not true on Cloud US,
                // where 3 projects exceed this limit. To accommodate those, we should always make a request for the
                // date range of the graph, and not rely on the annotations in the store.

                const filteredAnnotations = dateRange
                    ? annotations.filter(
                          (annotation: AnnotationType) =>
                              (annotation.scope !== AnnotationScope.Insight ||
                                  annotation.dashboard_item === insightNumericId) &&
                              (annotation.scope !== AnnotationScope.Dashboard ||
                                  annotation.dashboard_item === insightNumericId ||
                                  (dashboardId
                                      ? // on dashboard page, only show annotations if scoped to this dashboard
                                        annotation.dashboard_id === dashboardId
                                      : // on insight page, show annotation if insight is on any dashboard which this annotation is scoped to
                                        savedInsight?.dashboard_tiles?.find(
                                            ({ dashboard_id }) => dashboard_id === annotation.dashboard_id
                                        ))) &&
                              annotation.date_marker &&
                              annotation.date_marker >= dateRange[0] &&
                              annotation.date_marker < dateRange[1] &&
                              (!annotationsScope || annotation.scope === annotationsScope)
                      )
                    : []

                // Add special annotation for January 6th and 7th if person property filters or breakdown are present
                // The incident period was Jan 6, 8:01pm UTC - Jan 7, 2:52pm UTC
                if (
                    dateRange &&
                    hasPersonPropertyFiltersOrBreakdown(properties, breakdownFilter) &&
                    featureFlags[FEATURE_FLAGS.PERSON_PROPERTY_INCIDENT_ANNOTATION_JAN_2026]
                ) {
                    const incidentDates = ['2026-01-06', '2026-01-07']
                    const specialAnnotations: DatedAnnotationType[] = incidentDates
                        .map((dateStr, index) => {
                            const dateInTimezone = parseDateInTimezone(dateStr, timezone).startOf('day')

                            // Only include if date is within the date range
                            if (dateInTimezone >= dateRange[0] && dateInTimezone < dateRange[1]) {
                                return {
                                    id: -(index + 1), // -1 for Jan 6, -2 for Jan 7
                                    scope: AnnotationScope.Project,
                                    content:
                                        'Some person properties may have been set incorrectly on events between January 6, 20:01 UTC and January 7, 14:52 UTC. See https://status.posthog.com/ for more information.',
                                    date_marker: dateInTimezone,
                                    created_at: dayjs(),
                                    updated_at: dayjs().toISOString(),
                                    dashboard_item: null,
                                    deleted: false,
                                } as DatedAnnotationType
                            }
                            return null
                        })
                        .filter((annotation): annotation is DatedAnnotationType => annotation !== null)

                    if (specialAnnotations.length > 0) {
                        return [...filteredAnnotations, ...specialAnnotations] as DatedAnnotationType[]
                    }
                }

                return filteredAnnotations as DatedAnnotationType[]
            },
        ],
        groupedAnnotations: [
            (s) => [s.relevantAnnotations, s.intervalUnit],
            (relevantAnnotations: DatedAnnotationType[], intervalUnit: IntervalType) => {
                return groupBy(relevantAnnotations, (annotation) => {
                    return determineAnnotationsDateGroup(annotation.date_marker, intervalUnit)
                })
            },
        ],
        /** Fractional data-point indices for annotation badges, e.g. Dec 15 on a monthly chart
         *  lands at index ~0.48 between the Dec 1 and Jan 1 data points. */
        annotationBadgeDataIndices: [
            (s) => [
                s.groupedAnnotations,
                s.intervalUnit,
                s.timezone,
                (_, props: AnnotationsOverlayLogicProps) => props.dates,
            ],
            (
                groupedAnnotations: Record<number | string, DatedAnnotationType[]>,
                intervalUnit: IntervalType,
                timezone: string,
                dates: string[]
            ): Array<{ dateKey: string; date: Dayjs; dataIndex: number }> => {
                if (dates.length === 0) {
                    return []
                }
                // Interpolate between the actual data points instead of assuming one point per interval:
                // SQL charts can skip dates or bucket coarser than the insight interval.
                // SQL charts can have tens of thousands of points, so binary search and parse only the dates it visits.
                const pointTime = (index: number): number => parseDateInTimezone(dates[index], timezone).valueOf()
                const lastIndex = dates.length - 1
                return Object.entries(groupedAnnotations)
                    .map(([dateKey, annotations]) => {
                        const date = annotations[0].date_marker.startOf(getGroupingUnit(intervalUnit))
                        const time = date.valueOf()
                        let nextIndex = 0
                        let end = dates.length
                        while (nextIndex < end) {
                            const middle = (nextIndex + end) >> 1
                            if (pointTime(middle) > time) {
                                end = middle
                            } else {
                                nextIndex = middle + 1
                            }
                        }
                        // Before the first point → negative, filtered out below. Past the final point → snap
                        // onto it rather than extrapolating off the canvas.
                        if (nextIndex === dates.length) {
                            return { dateKey, date, dataIndex: lastIndex }
                        }
                        if (nextIndex === 0) {
                            return { dateKey, date, dataIndex: -1 }
                        }
                        const previousTime = pointTime(nextIndex - 1)
                        const dataIndex = nextIndex - 1 + (time - previousTime) / (pointTime(nextIndex) - previousTime)
                        return { dateKey, date, dataIndex }
                    })
                    .filter(({ dataIndex }) => dataIndex >= 0)
                    .sort((a, b) => a.dataIndex - b.dataIndex)
            },
        ],
    }),
])