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.

30.7 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'

import { IconCheckCircle, IconPlus, IconX, IconInfo } from '@posthog/icons'
import { LemonSelect, LemonSwitch } from '@posthog/lemon-ui'

import { EventSelect } from 'lib/components/EventSelect/EventSelect'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { timeZoneLabel } from 'lib/utils/timezones'
import { DatabaseTable } from 'scenes/data-management/database/DatabaseTable'
import { teamLogic } from 'scenes/teamLogic'

import { NodeKind } from '~/queries/schema/schema-general'
import {
    AnyPropertyFilter,
    BatchExportConfigurationTest,
    BatchExportConfigurationTestStep,
    IntegrationType,
} from '~/types'

import { BatchExportModelEnumApi } from 'products/batch_exports/frontend/generated/api.schemas'
import { SourceDestinationsBanner } from 'products/warehouse_sources/frontend/components/SourceDestinationsBanner'

import { batchExportConfigFormLogic } from './batchExportConfigFormLogic'
import {
    BatchExportConfigurationClearChangesButton,
    BatchExportConfigurationSaveButton,
} from './BatchExportConfigurationButtons'
import { BatchExportGeneralEditFields, BatchExportsEditFields } from './BatchExportEditForm'
import { BatchExportHogQLQueryEditor } from './BatchExportHogQLQueryEditor'
import { BatchExportQueryTimezoneSelector } from './BatchExportQueryTimezoneSelector'
import { EVENT_FIELD_DESCRIPTIONS } from './destinations/common'
import { BatchExportConfigurationForm } from './types'
import { dayOptions, hourOptions } from './utils'

export function BatchExportConfiguration(): JSX.Element {
    const {
        isNew,
        batchExportConfigTest,
        batchExportConfigTestLoading,
        configuration,
        tables,
        batchExportConfig,
        selectedModel,
        runningStep,
        isDatabaseDestination,
        service,
        selectedIntegration,
    } = useValues(batchExportConfigFormLogic)
    const { setConfigurationValue, runBatchExportConfigTestStep } = useActions(batchExportConfigFormLogic)
    const { featureFlags } = useValues(featureFlagLogic)
    const { preflight } = useValues(preflightLogic)
    const { timezone: teamTimezone, weekStartDay } = useValues(teamLogic)
    const highFrequencyBatchExports = featureFlags[FEATURE_FLAGS.HIGH_FREQUENCY_BATCH_EXPORTS]
    const hogqlBatchExports = !!featureFlags[FEATURE_FLAGS.HOGQL_BATCH_EXPORTS]
    const isHogQLModel = selectedModel === BatchExportModelEnumApi.Hogql

    const showTimezoneAndOffsetSelector = configuration.interval === 'day' || configuration.interval === 'week'
    const timezoneOptions =
        preflight?.available_timezones &&
        Object.entries(preflight.available_timezones).map(([tz, offset]) => ({
            key: tz,
            label: timeZoneLabel(tz, offset),
        }))

    const requiredFields = ['interval']
    const requiredFieldsMissing = requiredFields.filter((field) => !configuration[field])

    return (
        <Form logic={batchExportConfigFormLogic} formKey="configuration" className="flex flex-col gap-3">
            <SourceDestinationsBanner />
            <div className="flex flex-wrap gap-4 items-start">
                <div className="flex flex-col flex-1 min-w-100 gap-y-3">
                    <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2 *:max-w-160">
                        <div className="flex flex-col gap-y-1 mb-2">
                            <h3 className="mb-0">Schedule</h3>
                            <p className="text-secondary text-xs mb-0">Controls when this batch export runs</p>
                        </div>
                        <LemonField
                            label="Status"
                            name="paused"
                            info="Start in a paused state or continuously exporting from now"
                        >
                            {({ value, onChange }) => (
                                <LemonSwitch
                                    label="Enabled"
                                    onChange={() => onChange(!value)}
                                    checked={!value}
                                    fullWidth
                                    bordered
                                />
                            )}
                        </LemonField>

                        <div className="flex gap-2 min-h-16">
                            <LemonField
                                name="interval"
                                label="Interval"
                                className="flex-1"
                                info={
                                    <>
                                        Dictates the frequency of batch export runs. For example, if you select hourly,
                                        a new batch export run will start every hour.
                                    </>
                                }
                            >
                                <LemonSelect
                                    options={[
                                        { value: 'hour', label: 'Hourly' },
                                        { value: 'day', label: 'Daily' },
                                        { value: 'week', label: 'Weekly' },
                                        {
                                            value: 'every 5 minutes',
                                            label: 'Every 5 minutes',
                                            hidden: !highFrequencyBatchExports,
                                        },
                                        {
                                            value: 'every 15 minutes',
                                            label: 'Every 15 minutes',
                                            hidden: !highFrequencyBatchExports,
                                        },
                                    ]}
                                />
                            </LemonField>
                        </div>

                        {showTimezoneAndOffsetSelector && (
                            <>
                                {configuration.interval === 'day' && (
                                    <div className="flex gap-2 min-h-16">
                                        <LemonField
                                            name="offset_hour"
                                            label="Start time"
                                            className="flex-1"
                                            info="Time of day when the daily export should run"
                                        >
                                            {({ value, onChange }) => {
                                                const hour = value ?? 0
                                                return (
                                                    <LemonSelect
                                                        value={hour}
                                                        onChange={(newHour) => {
                                                            onChange(newHour ?? 0)
                                                        }}
                                                        options={hourOptions}
                                                    />
                                                )
                                            }}
                                        </LemonField>
                                    </div>
                                )}
                                {configuration.interval === 'week' && (
                                    <div className="flex items-end gap-2 min-h-16">
                                        <LemonField
                                            name="offset_day"
                                            label="Start time"
                                            className="flex-1"
                                            info="Day and time when the weekly export should run"
                                        >
                                            {({ value: dayValue, onChange: onChangeDay }) => {
                                                const defaultDay = weekStartDay ?? 0
                                                const day = dayValue ?? defaultDay
                                                return (
                                                    <LemonSelect
                                                        value={day}
                                                        onChange={(newDay) => {
                                                            onChangeDay(newDay ?? defaultDay)
                                                        }}
                                                        options={dayOptions}
                                                    />
                                                )
                                            }}
                                        </LemonField>
                                        <LemonField name="offset_hour" className="flex-1">
                                            {({ value: hourValue, onChange: onChangeHour }) => {
                                                const hour = hourValue ?? 0
                                                return (
                                                    <LemonSelect
                                                        value={hour}
                                                        onChange={(newHour) => {
                                                            onChangeHour(newHour ?? 0)
                                                        }}
                                                        options={hourOptions}
                                                    />
                                                )
                                            }}
                                        </LemonField>
                                    </div>
                                )}
                                <div className="flex gap-2 min-h-16">
                                    <LemonField
                                        name="timezone"
                                        label="Timezone"
                                        className="flex-1"
                                        info={`Timezone used for determining ${configuration.interval} boundaries when scheduling batch export runs. This does not change the timezone of the exported data.`}
                                    >
                                        {({ value, onChange }) => {
                                            const currentTimezone = value || teamTimezone || 'UTC'
                                            return (
                                                <LemonInputSelect
                                                    mode="single"
                                                    placeholder="Select a time zone"
                                                    value={[currentTimezone]}
                                                    onChange={(newValue) => {
                                                        onChange(newValue[0] || teamTimezone || 'UTC')
                                                    }}
                                                    options={timezoneOptions || []}
                                                    popoverClassName="z-[1000]"
                                                    virtualized
                                                />
                                            )
                                        }}
                                    </LemonField>
                                </div>
                            </>
                        )}
                    </div>
                    <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2 *:max-w-160">
                        <div className="flex flex-col gap-y-1 mb-2">
                            <h3 className="mb-0">Data</h3>
                            <p className="text-secondary text-xs mb-0">Controls which data is exported</p>
                        </div>
                        <div className="flex gap-2 min-h-16">
                            <LemonField
                                name="model"
                                label="Model"
                                info="A model defines the data that will be exported."
                                className="flex flex-1"
                            >
                                <LemonSelect
                                    options={[
                                        ...tables.map((table) => ({
                                            value: table.name,
                                            label: table.id,
                                        })),
                                        {
                                            value: BatchExportModelEnumApi.Hogql,
                                            label: 'Custom SQL query',
                                            hidden: !hogqlBatchExports,
                                        },
                                    ]}
                                    disabledReason={
                                        isNew
                                            ? undefined
                                            : "A saved batch export can't change its model. Create a new one to export different data."
                                    }
                                    fullWidth={true}
                                />
                            </LemonField>
                        </div>

                        {isHogQLModel ? (
                            <p className="text-xs text-secondary mb-0">
                                Each run exports the results of the query below.
                            </p>
                        ) : (
                            <div className="flex gap-2">
                                <LemonCollapse
                                    className="flex flex-1"
                                    panels={[
                                        {
                                            key: 'schema',
                                            header: 'View model schema',
                                            content: (
                                                <div className="flex-1">
                                                    {/* TODO: display the data types that will be used in the destination */}
                                                    {isDatabaseDestination && (
                                                        <LemonBanner type="info" className="mb-4">
                                                            This schema is just for reference and does not reflect the
                                                            actual data types that will be used in {service}.
                                                            <br />
                                                            <br />
                                                            <b>
                                                                It is recommended to allow the batch export to create
                                                                the destination table automatically.
                                                            </b>
                                                        </LemonBanner>
                                                    )}
                                                    <DatabaseTable
                                                        table={
                                                            selectedModel
                                                                ? selectedModel
                                                                : BatchExportModelEnumApi.Events
                                                        }
                                                        tables={tables}
                                                        inEditSchemaMode={false}
                                                        fieldDescriptions={
                                                            !selectedModel ||
                                                            selectedModel === BatchExportModelEnumApi.Events
                                                                ? EVENT_FIELD_DESCRIPTIONS
                                                                : undefined
                                                        }
                                                    />
                                                </div>
                                            ),
                                        },
                                    ]}
                                />
                            </div>
                        )}
                        {selectedModel === BatchExportModelEnumApi.Events ? (
                            <>
                                <div className="flex flex-col gap-2 min-h-16">
                                    <div className="flex gap-2 justify-between w-full">
                                        <LemonLabel>Include events</LemonLabel>
                                    </div>
                                    <p className="mb-0 text-xs text-secondary">
                                        If set, the batch export will <b>only</b> export events matching any of the
                                        below. If left unset, all events will be exported.
                                    </p>
                                    <EventSelect
                                        onChange={(includedEvents) => {
                                            const filteredEvents = includedEvents.filter((event) => event != null)
                                            setConfigurationValue('include_events', filteredEvents)
                                        }}
                                        selectedEvents={
                                            configuration.include_events ? configuration.include_events : []
                                        }
                                        addElement={
                                            <LemonButton
                                                size="small"
                                                type="secondary"
                                                icon={<IconPlus />}
                                                sideIcon={null}
                                            >
                                                Include event
                                            </LemonButton>
                                        }
                                    />
                                </div>
                                <div className="flex flex-col gap-2 min-h-16">
                                    <div className="flex gap-2 justify-between w-full">
                                        <LemonLabel>Exclude events</LemonLabel>
                                    </div>
                                    <p className="mb-0 text-xs text-secondary">
                                        If set, the batch export will <b>exclude</b> events matching any of the below.
                                        If left unset, no events will be excluded from the export.
                                    </p>
                                    <EventSelect
                                        onChange={(excludedEvents) => {
                                            const filteredEvents = excludedEvents.filter((event) => event != null)
                                            setConfigurationValue('exclude_events', filteredEvents)
                                        }}
                                        selectedEvents={
                                            configuration.exclude_events ? configuration.exclude_events : []
                                        }
                                        addElement={
                                            <LemonButton
                                                size="small"
                                                type="secondary"
                                                icon={<IconPlus />}
                                                sideIcon={null}
                                            >
                                                Exclude event
                                            </LemonButton>
                                        }
                                    />
                                </div>
                                <div className="flex gap-2 min-h-16">
                                    <LemonField name="filters" label="Filters" className="flex flex-1">
                                        <PropertyFilters
                                            propertyFilters={
                                                (configuration.filters
                                                    ? configuration.filters
                                                    : []) as AnyPropertyFilter[]
                                            }
                                            taxonomicGroupTypes={
                                                selectedModel === BatchExportModelEnumApi.Events
                                                    ? [
                                                          TaxonomicFilterGroupType.EventProperties,
                                                          TaxonomicFilterGroupType.EventFeatureFlags,
                                                          TaxonomicFilterGroupType.PersonProperties,
                                                          TaxonomicFilterGroupType.HogQLExpression,
                                                      ]
                                                    : []
                                            }
                                            onChange={(filters: AnyPropertyFilter[]) => {
                                                setConfigurationValue('filters', filters)
                                            }}
                                            pageKey={`BatchExportsPropertyFilters.${
                                                batchExportConfig ? batchExportConfig.id : 'New'
                                            }`}
                                            metadataSource={{ kind: NodeKind.ActorsQuery }}
                                        />
                                    </LemonField>
                                </div>
                            </>
                        ) : null}
                    </div>
                    {isHogQLModel ? (
                        <div className="flex flex-col p-3 rounded border bg-surface-primary gap-y-2">
                            <div className="flex flex-col gap-y-1 mb-2">
                                <h3 className="mb-0">Query</h3>
                                <p className="text-secondary text-xs mb-0">
                                    Write the SQL query whose results each run exports. Run it here to preview the data.
                                </p>
                            </div>
                            <div className="max-w-160 mb-2">
                                <BatchExportQueryTimezoneSelector />
                            </div>
                            <LemonField name="hogql_query">
                                <BatchExportHogQLQueryEditor />
                            </LemonField>
                        </div>
                    ) : null}
                </div>

                <div className="flex flex-col gap-4 flex-1 min-w-100">
                    <div className="p-3 rounded border bg-surface-primary *:max-w-160">
                        <BatchExportConfigurationFields
                            isNew={isNew}
                            formValues={configuration as BatchExportConfigurationForm}
                            savedConfig={batchExportConfig?.destination?.config ?? null}
                            selectedIntegration={selectedIntegration}
                        />
                    </div>
                    {batchExportConfigTest && (
                        <div className="p-3 rounded border bg-surface-primary">
                            <BatchExportConfigurationTests
                                batchExportConfigTest={batchExportConfigTest}
                                batchExportConfigTestLoading={batchExportConfigTestLoading}
                                runningStep={runningStep}
                                runBatchExportConfigTestStep={runBatchExportConfigTestStep}
                                requiredFieldsMissing={requiredFieldsMissing}
                            />
                        </div>
                    )}
                </div>
            </div>
            <div className="flex gap-2 justify-end">
                <BatchExportConfigurationClearChangesButton />
                <BatchExportConfigurationSaveButton />
            </div>
        </Form>
    )
}

function BatchExportConfigurationFields({
    isNew,
    formValues,
    savedConfig,
    selectedIntegration,
}: {
    isNew: boolean
    formValues: BatchExportConfigurationForm
    savedConfig: Record<string, any> | null
    selectedIntegration: IntegrationType | null
}): JSX.Element {
    return (
        <>
            <BatchExportGeneralEditFields isNew={isNew} isPipeline batchExportConfigForm={formValues} />
            <BatchExportsEditFields
                isNew={isNew}
                batchExportConfigForm={formValues}
                savedConfig={savedConfig}
                selectedIntegration={selectedIntegration}
            />
        </>
    )
}

export function BatchExportConfigurationTests({
    batchExportConfigTest,
    batchExportConfigTestLoading,
    runningStep,
    runBatchExportConfigTestStep,
    requiredFieldsMissing,
}: {
    batchExportConfigTest: BatchExportConfigurationTest
    batchExportConfigTestLoading: boolean
    runningStep: number | null
    runBatchExportConfigTestStep: (step: any) => void
    requiredFieldsMissing: string[]
}): JSX.Element | null {
    if (!batchExportConfigTest && batchExportConfigTestLoading) {
        return (
            <div className="flex justify-center items-center p-4">
                <Spinner />
            </div>
        )
    }

    if (!batchExportConfigTest || !batchExportConfigTest.steps) {
        return null
    }

    const renderStatusIcon = (step: BatchExportConfigurationTestStep, index: number): JSX.Element => {
        if (!step.result || runningStep === index) {
            return <Spinner />
        }

        return step.result.status === 'Passed' ? (
            <IconCheckCircle className="text-green-500 shrink-0" />
        ) : step.result.status === 'Skipped' ? (
            <IconInfo className="text-yellow-500 shrink-0" />
        ) : (
            <IconX className="text-red-500 shrink-0" />
        )
    }

    const header = (
        <div className="space-y-2">
            <h2 className="flex gap-2 items-center m-0 text-lg font-semibold">Test configuration</h2>
            <p className="text-xs text-secondary">
                Test the batch export's configuration to uncover errors before saving it
            </p>
        </div>
    )

    if (requiredFieldsMissing.length > 0) {
        return (
            <div className="space-y-4">
                {header}
                <LemonBanner type="info">
                    Please select a value for the following fields before testing the configuration:{' '}
                    {requiredFieldsMissing.join(', ')}
                </LemonBanner>
            </div>
        )
    }

    return (
        <div className="space-y-4">
            <div className="flex justify-between items-center">
                {header}
                <LemonButton
                    onClick={() => runBatchExportConfigTestStep(0)}
                    disabledReason={runningStep !== null ? 'Test step is running' : null}
                    size="small"
                    type="primary"
                >
                    {runningStep ? 'Testing...' : 'Start test'}
                </LemonButton>
            </div>

            <div className="space-y-4">
                {batchExportConfigTest.steps.map((step, index) => {
                    // Only render if the step has a result or is currently running
                    if (!step.result && index !== runningStep) {
                        return null
                    }

                    return (
                        <div key={`${step.name}-${index}`}>
                            <div className="flex gap-2 items-start">
                                <div className="mt-px">{renderStatusIcon(step, index)}</div>
                                <div className="flex-1">
                                    <LemonLabel info={step.description} className="mb-2">
                                        {step.name}
                                    </LemonLabel>
                                    {step.result && (
                                        <div className="mt-2">
                                            <LemonBanner
                                                type={
                                                    step.result.status === 'Passed'
                                                        ? 'success'
                                                        : step.result.status === 'Skipped'
                                                          ? 'info'
                                                          : 'error'
                                                }
                                            >
                                                {step.result.status === 'Passed' ? 'Success' : `${step.result.message}`}
                                            </LemonBanner>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )
                })}
            </div>
        </div>
    )
}