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.

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

import api from 'lib/api'
import { dayjsUtcToTimezone } from 'lib/dayjs'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'

import { AnnotationType, RawAnnotationType } from '~/types'

import type { TeamPublicType, TeamType } from '../types'

export type AnnotationData = Pick<RawAnnotationType, 'date_marker' | 'scope' | 'content' | 'dashboard_item'>
export type AnnotationDataWithoutInsight = Omit<AnnotationData, 'dashboard_item'>

export function deserializeAnnotation(annotation: RawAnnotationType, projectTimezone: string): AnnotationType {
    return {
        ...annotation,
        date_marker: annotation.date_marker ? dayjsUtcToTimezone(annotation.date_marker, projectTimezone) : null,
        created_at: dayjsUtcToTimezone(annotation.created_at, projectTimezone),
    }
}

export function serializeAnnotation(annotation: AnnotationType): RawAnnotationType {
    return {
        ...annotation,
        date_marker: annotation.date_marker ? annotation.date_marker.toISOString() : null,
        created_at: annotation.created_at.toISOString(),
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsModelValues {
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    timezone: string // teamLogic
    annotations: AnnotationType[]
    annotationsLoading: boolean
    loadingNext: boolean
    next: string | null
    rawAnnotations: RawAnnotationType[]
    rawAnnotationsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsModelActions {
    appendAnnotations: (annotations: RawAnnotationType[]) => {
        annotations: RawAnnotationType[]
    }
    createAnnotationGenerically: (annotationData: AnnotationData) => AnnotationData
    createAnnotationGenericallyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createAnnotationGenericallySuccess: (
        rawAnnotations: void,
        payload?: AnnotationData
    ) => {
        rawAnnotations: void
        payload?: AnnotationData
    }
    deleteAnnotation: (annotation: AnnotationType) => {
        annotation: AnnotationType
    }
    deleteAnnotationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteAnnotationSuccess: (
        rawAnnotations: AnnotationType[],
        payload?: {
            annotation: AnnotationType
        }
    ) => {
        rawAnnotations: AnnotationType[]
        payload?: {
            annotation: AnnotationType
        }
    }
    loadAnnotations: () => any
    loadAnnotationsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAnnotationsNext: () => boolean
    loadAnnotationsSuccess: (
        rawAnnotations: RawAnnotationType[],
        payload?: any
    ) => {
        rawAnnotations: RawAnnotationType[]
        payload?: any
    }
    replaceAnnotation: (annotation: RawAnnotationType) => {
        annotation: RawAnnotationType
    }
    setNext: (next: string | null) => {
        next: string | null
    }
    updateAnnotation: ({
        annotationId,
        annotationData,
    }: {
        annotationData: AnnotationDataWithoutInsight
        annotationId: RawAnnotationType['id']
    }) => {
        annotationId: RawAnnotationType[]
        annotationData: AnnotationDataWithoutInsight
    }
    updateAnnotationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateAnnotationSuccess: (
        rawAnnotations: void,
        payload?: {
            annotationId: RawAnnotationType[]
            annotationData: AnnotationDataWithoutInsight
        }
    ) => {
        rawAnnotations: void
        payload?: {
            annotationId: RawAnnotationType[]
            annotationData: AnnotationDataWithoutInsight
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface annotationsModelMeta {
    __keaTypeGenInternalSelectorTypes: {
        annotations: (rawAnnotations: RawAnnotationType[], timezone: string) => AnnotationType[]
        annotationsLoading: (rawAnnotationsLoading: boolean) => boolean
    }
}

export type annotationsModelType = MakeLogicType<
    annotationsModelValues,
    annotationsModelActions,
    Record<string, any>,
    annotationsModelMeta
>

export const annotationsModel = kea<annotationsModelType>([
    path(['models', 'annotationsModel']),
    connect(() => ({ values: [teamLogic, ['currentTeam', 'timezone']] })),
    actions({
        deleteAnnotation: (annotation: AnnotationType) => ({ annotation }),
        loadAnnotationsNext: () => true,
        setNext: (next: string | null) => ({ next }),
        appendAnnotations: (annotations: RawAnnotationType[]) => ({ annotations }),
        replaceAnnotation: (annotation: RawAnnotationType) => ({ annotation }),
    }),
    loaders(({ values, actions }) => ({
        rawAnnotations: {
            __default: [],
            loadAnnotations: async () => {
                const response = await api.annotations.list({ hidden_in_user_interface: false })
                actions.setNext(response.next || null)
                return response.results
            },
            createAnnotationGenerically: async (annotationData: AnnotationData) => {
                const createdAnnotation = await api.annotations.create(annotationData)
                actions.appendAnnotations([createdAnnotation])
            },
            updateAnnotation: async ({
                annotationId,
                annotationData,
            }: {
                annotationId: RawAnnotationType['id']
                annotationData: AnnotationDataWithoutInsight
            }) => {
                const updatedAnnotation = await api.annotations.update(annotationId, annotationData)
                actions.replaceAnnotation(updatedAnnotation)
            },
            deleteAnnotation: async ({ annotation }) => {
                await deleteWithUndo({
                    endpoint: api.annotations.determineDeleteEndpoint(),
                    object: { name: `${annotation.date_marker} annotation`, ...annotation },
                    callback: (undo, annotation) => {
                        if (undo) {
                            actions.appendAnnotations([serializeAnnotation(annotation)])
                        }
                    },
                })
                return values.annotations.filter((a) => a.id !== annotation.id)
            },
        },
    })),
    reducers(() => ({
        rawAnnotations: [
            [] as RawAnnotationType[],
            {
                appendAnnotations: (state, { annotations }) => [...state, ...annotations],
                replaceAnnotation: (state, { annotation }) => {
                    const copy = state.slice()
                    const index = copy.findIndex((iterationAnnotation) => iterationAnnotation.id === annotation.id)
                    copy[index] = annotation
                    return copy
                },
            },
        ],
        next: [
            null as string | null,
            {
                setNext: (_, { next }) => next,
            },
        ],
        loadingNext: [
            false,
            {
                loadAnnotationsNext: () => true,
                appendAnnotations: () => false,
            },
        ],
    })),
    selectors({
        annotations: [
            (s) => [s.rawAnnotations, s.timezone],
            (rawAnnotations: RawAnnotationType[], timezone: string): AnnotationType[] => {
                return rawAnnotations.map((annotation): AnnotationType => deserializeAnnotation(annotation, timezone))
            },
        ],
        annotationsLoading: [
            (s) => [s.rawAnnotationsLoading],
            (rawAnnotationsLoading: boolean) => rawAnnotationsLoading,
        ],
    }),
    listeners(({ actions, values }) => ({
        loadAnnotationsNext: async () => {
            let results: RawAnnotationType[] = []
            if (values.next) {
                // 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(values.next)
                actions.setNext(response.next)
                results = response.results
            }
            actions.appendAnnotations(results)
        },
    })),
    afterMount(({ values, actions }) => {
        if (isAuthenticatedTeam(values.currentTeam)) {
            // Don't load on shared insights/dashboards
            actions.loadAnnotations()
        }
    }),
    permanentlyMount(),
])