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.

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

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

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

export enum MaterializedColumnSlotState {
    PENDING = 'PENDING',
    BACKFILL = 'BACKFILL',
    READY = 'READY',
    ERROR = 'ERROR',
}

export interface PropertyDefinition {
    id: number
    name: string
    property_type: string
    type: number
}

export interface MaterializedColumnSlot {
    id: string
    team: number
    property_definition: number
    property_definition_details: PropertyDefinition
    /** Null while in PENDING — a column is only assigned once the weekly workflow runs. */
    slot_index: number | null
    state: MaterializedColumnSlotState
    backfill_temporal_run_id: string | null
    error_message: string | null
    created_at: string
    updated_at: string
}

export interface SlotUsageSummary {
    team_id: number
    team_name: string
    max_slots_per_team: number
    used_total: number
    available: number
}

export interface AutoMaterializedColumn {
    column_name: string
    property_name: string
    table_column: string
    is_disabled: boolean
    is_nullable: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface materializedColumnsLogicValues {
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    autoMaterializedColumns: AutoMaterializedColumn[]
    autoMaterializedColumnsLoading: boolean
    availableProperties: PropertyDefinition[]
    availablePropertiesLoading: boolean
    canAssignMoreSlots: boolean
    showCreateModal: boolean
    slotUsage: SlotUsageSummary | null
    slotUsageLoading: boolean
    slots: MaterializedColumnSlot[]
    slotsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface materializedColumnsLogicActions {
    deleteSlot: (slotId: string) => {
        slotId: string
    }
    loadAutoMaterializedColumns: () => any
    loadAutoMaterializedColumnsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAutoMaterializedColumnsSuccess: (
        autoMaterializedColumns: AutoMaterializedColumn[],
        payload?: any
    ) => {
        autoMaterializedColumns: AutoMaterializedColumn[]
        payload?: any
    }
    loadAvailableProperties: () => any
    loadAvailablePropertiesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAvailablePropertiesSuccess: (
        availableProperties: PropertyDefinition[],
        payload?: any
    ) => {
        availableProperties: PropertyDefinition[]
        payload?: any
    }
    loadSlotUsage: () => any
    loadSlotUsageFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSlotUsageSuccess: (
        slotUsage: SlotUsageSummary | null,
        payload?: any
    ) => {
        slotUsage: SlotUsageSummary | null
        payload?: any
    }
    loadSlots: () => any
    loadSlotsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSlotsSuccess: (
        slots: MaterializedColumnSlot[],
        payload?: any
    ) => {
        slots: MaterializedColumnSlot[]
        payload?: any
    }
    retrySlot: (slotId: string) => {
        slotId: string
    }
    setShowCreateModal: (show: boolean) => {
        show: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface materializedColumnsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        canAssignMoreSlots: (slotUsage: SlotUsageSummary | null) => boolean
    }
}

export type materializedColumnsLogicType = MakeLogicType<
    materializedColumnsLogicValues,
    materializedColumnsLogicActions,
    Record<string, any>,
    materializedColumnsLogicMeta
>

export const materializedColumnsLogic = kea<materializedColumnsLogicType>([
    path(['scenes', 'data-management', 'MaterializedColumns', 'materializedColumnsLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeam']],
    })),
    actions({
        setShowCreateModal: (show: boolean) => ({ show }),
        deleteSlot: (slotId: string) => ({ slotId }),
        retrySlot: (slotId: string) => ({ slotId }),
    }),
    loaders(({ values }) => ({
        slots: [
            [] as MaterializedColumnSlot[],
            {
                loadSlots: async () => {
                    if (!values.currentTeam) {
                        return []
                    }
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    const response = await api.get(`api/projects/${values.currentTeam.id}/materialized_column_slots/`)
                    return response.results || []
                },
            },
        ],
        slotUsage: [
            null as SlotUsageSummary | null,
            {
                loadSlotUsage: async () => {
                    if (!values.currentTeam) {
                        return null
                    }
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    return await api.get(`api/projects/${values.currentTeam.id}/materialized_column_slots/slot_usage/`)
                },
            },
        ],
        availableProperties: [
            [] as PropertyDefinition[],
            {
                loadAvailableProperties: async () => {
                    if (!values.currentTeam) {
                        return []
                    }
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    return await api.get(
                        `api/projects/${values.currentTeam.id}/materialized_column_slots/available_properties/`
                    )
                },
            },
        ],
        autoMaterializedColumns: [
            [] as AutoMaterializedColumn[],
            {
                loadAutoMaterializedColumns: async () => {
                    if (!values.currentTeam) {
                        return []
                    }
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    return await api.get(
                        `api/projects/${values.currentTeam.id}/materialized_column_slots/auto_materialized/`
                    )
                },
            },
        ],
    })),
    reducers({
        showCreateModal: [
            false,
            {
                setShowCreateModal: (_, { show }) => show,
            },
        ],
    }),
    selectors({
        canAssignMoreSlots: [
            (s) => [s.slotUsage],
            (slotUsage: SlotUsageSummary | null): boolean => {
                if (!slotUsage) {
                    return false
                }
                return slotUsage.available > 0
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        loadSlotsSuccess: () => {
            actions.loadSlotUsage()
        },
        setShowCreateModal: ({ show }) => {
            if (show) {
                actions.loadAvailableProperties()
            }
        },
        deleteSlot: async ({ slotId }) => {
            try {
                if (!values.currentTeam) {
                    return
                }
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                await api.delete(`api/projects/${values.currentTeam.id}/materialized_column_slots/${slotId}/`)
                lemonToast.success('Slot deleted successfully')
                actions.loadSlots()
            } catch (error) {
                lemonToast.error('Failed to delete slot')
                console.error(error)
            }
        },
        retrySlot: async ({ slotId }) => {
            try {
                if (!values.currentTeam) {
                    return
                }
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                await api.create(
                    `api/projects/${values.currentTeam.id}/materialized_column_slots/${slotId}/retry_backfill/`,
                    {}
                )
                lemonToast.success('Slot re-queued — it will be picked up by the next weekly backfill cycle')
                actions.loadSlots()
            } catch (error) {
                lemonToast.error('Failed to re-queue slot')
                console.error(error)
            }
        },
    })),
    events(({ actions }) => ({
        afterMount: () => {
            actions.loadSlots()
            actions.loadAutoMaterializedColumns()
        },
    })),
])