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.9 KB
Raw Blame
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import { useEffect } from 'react'

import { LemonButton, LemonSelect, LemonTag } from '@posthog/lemon-ui'

import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
import { IntegrationSettingsModal } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/IntegrationSettingsModal'
import {
    SetupSection,
    marketingAnalyticsLogic,
} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'

import { conversionGoalFormLogic } from 'products/marketing_analytics/frontend/setup/conversionGoalFormLogic'
import { ConversionGoalRecommendations } from 'products/marketing_analytics/frontend/setup/ConversionGoalRecommendations'
import { dashboardSetupPromptsLogic } from 'products/marketing_analytics/frontend/setup/dashboardSetupPromptsLogic'

import { runNavigateOp } from './navigateOps'
import { suggestionsForSection } from './sectionRouting'
import { SectionSuggestions } from './SectionSuggestions'
import { SETUP_SECTIONS } from './setupSections'
import { SuggestionModal } from './SuggestionModal'

/** Count of open suggestions in a section, and whether any of them is blocking.
 * Shown in the nav so you can see where the problems are without opening each one. */
function SectionBadge({
    suggestions,
    section,
}: {
    suggestions: Suggestion[]
    section: SetupSection
}): JSX.Element | null {
    const forSection = suggestionsForSection(suggestions, section)
    if (!forSection.length) {
        return null
    }
    const hasError = forSection.some((suggestion) => suggestion.severity === 'error')
    return (
        <LemonTag type={hasError ? 'danger' : 'warning'} size="small">
            {forSection.length}
        </LemonTag>
    )
}

export function SetupTab(): JSX.Element {
    const { currentTeamId } = useValues(teamLogic)
    const { user } = useValues(userLogic)
    const promptsLogic = dashboardSetupPromptsLogic({ projectId: currentTeamId ?? -1, userId: user?.uuid })
    const { dismissed } = useValues(promptsLogic)
    const { restore } = useActions(promptsLogic)
    const { selectRecommendation, requestFormFocus } = useActions(
        conversionGoalFormLogic({ projectId: currentTeamId ?? -1 })
    )
    const { featureFlags } = useValues(featureFlagLogic)
    const { setupSection } = useValues(marketingAnalyticsLogic)
    const { setSetupSection } = useActions(marketingAnalyticsLogic)
    const {
        setupPlan,
        setupPlanLoading,
        sourceScanDisabledReason,
        visibleSuggestions,
        reviewingSuggestion,
        isReviewingBatch,
        safeBatch,
        applyingIds,
    } = useValues(setupPlanLogic)
    const { loadSetupPlan, rescanSources, reviewSuggestion, confirmReviewedSuggestion, confirmReviewedBatch } =
        useActions(setupPlanLogic)
    const { integrationSettingsModal, setupEntryPointLabel } = useValues(marketingAnalyticsSettingsLogic)
    const { closeIntegrationSettingsModal } = useActions(marketingAnalyticsSettingsLogic)

    // Keep the audit gated for one release so the two flags can roll independently;
    // drop this once Setup is the only way in.
    const sections = SETUP_SECTIONS.filter(
        (section) =>
            section.key !== SetupSection.INTEGRATION_HEALTH || featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_UTM_AUDIT]
    )

    // Once on arrival and never again on its own — the plan is six ClickHouse queries
    // deep, one unioning every ad adapter.
    useEffect(() => {
        if (!setupPlan) {
            loadSetupPlan()
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    const active = sections.find((section) => section.key === setupSection) ?? sections[0]
    const dismissedPrompt =
        active.key === SetupSection.SOURCES && dismissed.sources
            ? 'sources'
            : active.key === SetupSection.CONVERSION_GOALS && dismissed['conversion-goals']
              ? 'conversion-goals'
              : null

    useEffect(() => {
        posthog.capture('marketing analytics setup section viewed', {
            section: active.key,
            entry_point: setupEntryPointLabel,
        })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [active.key])

    return (
        <div className="flex flex-col @min-[48rem]/main-content:flex-row gap-6 mt-4">
            <div className="@min-[48rem]/main-content:hidden">
                <LemonSelect
                    fullWidth
                    value={active.key}
                    onChange={setSetupSection}
                    options={sections.map((section) => ({ value: section.key, label: section.label }))}
                    aria-label="Setup section"
                />
            </div>
            <nav className="hidden @min-[48rem]/main-content:flex w-56 shrink-0 flex-col gap-px">
                {sections.map((section) => (
                    <LemonButton
                        key={section.key}
                        size="small"
                        fullWidth
                        active={section.key === active.key}
                        onClick={() => setSetupSection(section.key)}
                        sideIcon={<SectionBadge suggestions={visibleSuggestions} section={section.key} />}
                    >
                        {section.label}
                    </LemonButton>
                ))}
            </nav>

            <div className="grow min-w-0 deprecated-space-y-4">
                <div>
                    <h2 className="mb-1">{active.label}</h2>
                    {active.description && <p className="text-secondary mb-0">{active.description}</p>}
                </div>
                {dismissedPrompt && (
                    <LemonButton
                        type="secondary"
                        onClick={() => restore(dismissedPrompt)}
                        data-attr="marketing-restore-dashboard-suggestions"
                    >
                        Show suggestions on dashboard
                    </LemonButton>
                )}
                {/* Skipped for "Suggested setup", which renders the whole ranked list
                    itself and would otherwise show everything twice. */}
                {active.key !== SetupSection.SUGGESTIONS && active.key !== SetupSection.SOURCES && (
                    <SectionSuggestions section={active.key} />
                )}
                {featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI] &&
                    (active.key === SetupSection.SUGGESTIONS || active.key === SetupSection.CONVERSION_GOALS) && (
                        <ConversionGoalRecommendations
                            onConfigureGoals={() => {
                                setSetupSection(SetupSection.CONVERSION_GOALS)
                                requestFormFocus()
                            }}
                            onUseSuggestion={(recommendation) => {
                                selectRecommendation(recommendation)
                                setSetupSection(SetupSection.CONVERSION_GOALS)
                            }}
                        />
                    )}
                {active.key === SetupSection.SOURCES && (
                    <LemonButton
                        size="small"
                        loading={setupPlanLoading}
                        onClick={rescanSources}
                        disabledReason={sourceScanDisabledReason}
                        data-attr="marketing-sources-rescan"
                    >
                        Scan events again
                    </LemonButton>
                )}
                {active.content}
            </div>

            {/* At the tab, not in a section: a row anywhere can open either, and they
                must survive the user switching sections behind them. */}
            <SuggestionModal
                suggestion={reviewingSuggestion}
                batch={isReviewingBatch ? safeBatch : []}
                isApplying={
                    isReviewingBatch
                        ? safeBatch.some((item) => applyingIds.includes(item.id))
                        : !!reviewingSuggestion && applyingIds.includes(reviewingSuggestion.id)
                }
                onClose={() => reviewSuggestion(null)}
                onConfirm={(item) => {
                    // Navigate ops finish here; everything else goes to the server.
                    if (item.apply && runNavigateOp(item.apply, setupEntryPointLabel)) {
                        reviewSuggestion(null)
                        return
                    }
                    confirmReviewedSuggestion(item)
                }}
                onConfirmBatch={confirmReviewedBatch}
            />
            {/* UtmAuditTab renders this same modal off the same shared state, so the
                Integration health section would mount two copies of it. */}
            {integrationSettingsModal.integration && active.key !== SetupSection.INTEGRATION_HEALTH && (
                <IntegrationSettingsModal
                    integrationName={integrationSettingsModal.integration}
                    isOpen={integrationSettingsModal.isOpen}
                    onClose={closeIntegrationSettingsModal}
                    initialTab={integrationSettingsModal.initialTab}
                    initialUtmValue={integrationSettingsModal.initialUtmValue}
                    initialCampaignName={integrationSettingsModal.initialCampaignName}
                />
            )}
        </div>
    )
}